Merge main into fix/twist-boundary-tangent

This commit is contained in:
dotCooCoo
2026-11-17 13:42:02 -08:00
161 changed files with 6504 additions and 823 deletions
Generated
+73 -127
View File
@@ -1001,7 +1001,7 @@ dependencies = [
[[package]]
name = "craft-affinity"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
dependencies = [
"crc32fast",
"flate2",
@@ -1012,17 +1012,25 @@ dependencies = [
[[package]]
name = "craft-codepage"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
[[package]]
name = "craft-dds"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
dependencies = [
"rayon",
]
[[package]]
name = "craft-docpath"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
[[package]]
name = "craft-dxf"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
dependencies = [
"craft-codepage",
"encoding_rs",
@@ -1034,17 +1042,17 @@ dependencies = [
[[package]]
name = "craft-eps"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
[[package]]
name = "craft-fonts-build"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
[[package]]
name = "craft-gif"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
dependencies = [
"gif",
]
@@ -1052,7 +1060,7 @@ dependencies = [
[[package]]
name = "craft-gzip"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
dependencies = [
"flate2",
]
@@ -1060,7 +1068,7 @@ dependencies = [
[[package]]
name = "craft-i18n"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
dependencies = [
"fixed_decimal",
"icu_decimal",
@@ -1083,37 +1091,12 @@ dependencies = [
[[package]]
name = "craft-image-codecs"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=431f704478962677ec47e512754464d372901830#431f704478962677ec47e512754464d372901830"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
dependencies = [
"craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=431f704478962677ec47e512754464d372901830)",
"craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=431f704478962677ec47e512754464d372901830)",
"craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=431f704478962677ec47e512754464d372901830)",
"crc32fast",
"exr",
"flate2",
"half",
"hayro-jpeg2000",
"image",
"image-webp",
"jpeg-encoder",
"png 0.18.1",
"rayon",
"serde_json",
"thiserror 2.0.21",
"tiff",
"zune-core",
"zune-jpeg",
"zune-jpegxl",
]
[[package]]
name = "craft-image-codecs"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
dependencies = [
"craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)",
"craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)",
"craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)",
"craft-dds",
"craft-jpeg",
"craft-metadata",
"craft-tiff",
"crc32fast",
"exr",
"flate2",
@@ -1135,15 +1118,7 @@ dependencies = [
[[package]]
name = "craft-jpeg"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=431f704478962677ec47e512754464d372901830#431f704478962677ec47e512754464d372901830"
dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-jpeg"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
dependencies = [
"thiserror 2.0.21",
]
@@ -1151,7 +1126,7 @@ dependencies = [
[[package]]
name = "craft-jxl"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
dependencies = [
"jixel",
"jxl-oxide",
@@ -1161,7 +1136,7 @@ dependencies = [
[[package]]
name = "craft-keymap"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
dependencies = [
"egui",
"serde",
@@ -1171,23 +1146,11 @@ dependencies = [
[[package]]
name = "craft-metadata"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=431f704478962677ec47e512754464d372901830#431f704478962677ec47e512754464d372901830"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
dependencies = [
"brotli-decompressor 6.3.2",
"chrono",
"craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=431f704478962677ec47e512754464d372901830)",
"quick-xml 0.41.0",
"serde",
]
[[package]]
name = "craft-metadata"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
dependencies = [
"brotli-decompressor 6.3.2",
"chrono",
"craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)",
"craft-tiff",
"quick-xml 0.41.0",
"serde",
]
@@ -1195,7 +1158,7 @@ dependencies = [
[[package]]
name = "craft-metafile"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
dependencies = [
"encoding_rs",
"image",
@@ -1206,7 +1169,7 @@ dependencies = [
[[package]]
name = "craft-mime"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
dependencies = [
"chrono",
"craft-codepage",
@@ -1216,7 +1179,7 @@ dependencies = [
[[package]]
name = "craft-pdf"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e#0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
dependencies = [
"hayro-interpret",
"hayro-syntax",
@@ -1235,7 +1198,7 @@ dependencies = [
[[package]]
name = "craft-print"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
dependencies = [
"craft-winprint-gdi",
"log",
@@ -1249,7 +1212,7 @@ dependencies = [
[[package]]
name = "craft-proof"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
dependencies = [
"log",
"miniz_oxide 0.9.1",
@@ -1260,7 +1223,7 @@ dependencies = [
[[package]]
name = "craft-ps"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a80c0f25f1c4767374a27a444fbf95e3e8162e14#a80c0f25f1c4767374a27a444fbf95e3e8162e14"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
dependencies = [
"flate2",
"kurbo 0.13.1",
@@ -1269,7 +1232,7 @@ dependencies = [
[[package]]
name = "craft-psd"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
dependencies = [
"encoding_rs",
"flate2",
@@ -1280,7 +1243,7 @@ dependencies = [
[[package]]
name = "craft-stream-codecs"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e#0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
dependencies = [
"fax",
"hayro-ccitt",
@@ -1291,10 +1254,10 @@ dependencies = [
[[package]]
name = "craft-svg"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=431f704478962677ec47e512754464d372901830#431f704478962677ec47e512754464d372901830"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
dependencies = [
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=431f704478962677ec47e512754464d372901830)",
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=431f704478962677ec47e512754464d372901830)",
"craft-image-codecs",
"craft-xml",
"data-url",
"flate2",
"kurbo 0.13.1",
@@ -1310,16 +1273,7 @@ dependencies = [
[[package]]
name = "craft-tiff"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=431f704478962677ec47e512754464d372901830#431f704478962677ec47e512754464d372901830"
dependencies = [
"serde",
"thiserror 2.0.21",
]
[[package]]
name = "craft-tiff"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
dependencies = [
"serde",
"thiserror 2.0.21",
@@ -1328,7 +1282,7 @@ dependencies = [
[[package]]
name = "craft-ui"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
dependencies = [
"craft-fonts-build",
"craft-i18n",
@@ -1349,7 +1303,7 @@ dependencies = [
[[package]]
name = "craft-update"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
dependencies = [
"chrono",
"dunce",
@@ -1376,7 +1330,7 @@ dependencies = [
[[package]]
name = "craft-vectorcraft-format"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
dependencies = [
"flate2",
"serde",
@@ -1387,7 +1341,7 @@ dependencies = [
[[package]]
name = "craft-web-api"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=fd5e2feff6ea25bed371a99cc732b3968d621505#fd5e2feff6ea25bed371a99cc732b3968d621505"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
dependencies = [
"js-sys",
"serde_json",
@@ -1398,7 +1352,7 @@ dependencies = [
[[package]]
name = "craft-window"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
dependencies = [
"egui",
"objc2 0.6.5",
@@ -1417,17 +1371,7 @@ dependencies = [
[[package]]
name = "craft-xml"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=431f704478962677ec47e512754464d372901830#431f704478962677ec47e512754464d372901830"
dependencies = [
"quick-xml 0.41.0",
"serde",
"thiserror 2.0.21",
]
[[package]]
name = "craft-xml"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
dependencies = [
"quick-xml 0.41.0",
"serde",
@@ -2534,7 +2478,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a"
[[package]]
name = "hayro-cmap"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e#0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
dependencies = [
"brotli",
"hayro-postscript",
@@ -2543,7 +2487,7 @@ dependencies = [
[[package]]
name = "hayro-interpret"
version = "0.7.0"
source = "git+https://github.com/storytold/craft-libs?rev=0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e#0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
dependencies = [
"bitflags 2.13.2",
"hayro-cmap",
@@ -2561,7 +2505,7 @@ dependencies = [
[[package]]
name = "hayro-jbig2"
version = "0.3.0"
source = "git+https://github.com/storytold/craft-libs?rev=0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e#0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
dependencies = [
"fearless_simd",
"hayro-ccitt",
@@ -2579,12 +2523,12 @@ dependencies = [
[[package]]
name = "hayro-postscript"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e#0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
[[package]]
name = "hayro-syntax"
version = "0.7.2"
source = "git+https://github.com/storytold/craft-libs?rev=0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e#0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
dependencies = [
"flate2",
"hayro-ccitt",
@@ -3384,7 +3328,7 @@ dependencies = [
[[package]]
name = "krilla"
version = "0.8.2"
source = "git+https://github.com/storytold/craft-libs?rev=0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e#0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
dependencies = [
"base64 0.22.1",
"bumpalo",
@@ -3493,7 +3437,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4"
[[package]]
name = "linesweeper"
version = "0.5.0"
source = "git+https://github.com/storytold/craft-libs?rev=0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e#0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
dependencies = [
"arrayvec",
"kurbo 0.13.1",
@@ -6698,7 +6642,7 @@ name = "vectorcraft-affinity"
version = "0.24.1"
dependencies = [
"craft-affinity",
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)",
"craft-image-codecs",
"crc32fast",
"proptest",
]
@@ -6727,7 +6671,7 @@ name = "vectorcraft-cad"
version = "0.24.1"
dependencies = [
"craft-dxf",
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)",
"craft-image-codecs",
"craft-plotter",
"image",
"kurbo 0.13.1",
@@ -6781,7 +6725,7 @@ name = "vectorcraft-doc"
version = "0.24.1"
dependencies = [
"chrono",
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)",
"craft-image-codecs",
"craft-stream-codecs",
"flate2",
"image",
@@ -6801,7 +6745,7 @@ dependencies = [
name = "vectorcraft-effects"
version = "0.24.1"
dependencies = [
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)",
"craft-image-codecs",
"craft-svg",
"image",
"kurbo 0.13.1",
@@ -6825,11 +6769,11 @@ dependencies = [
"cfb",
"chrono",
"craft-docpath",
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)",
"craft-image-codecs",
"craft-jxl",
"craft-proof",
"craft-stream-codecs",
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)",
"craft-xml",
"crc32fast",
"flate2",
"hayro-ccitt",
@@ -6882,7 +6826,7 @@ name = "vectorcraft-eps"
version = "0.24.1"
dependencies = [
"craft-eps",
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)",
"craft-image-codecs",
"craft-pdf",
"craft-ps",
"craft-stream-codecs",
@@ -6962,7 +6906,7 @@ dependencies = [
name = "vectorcraft-mcp"
version = "0.24.1"
dependencies = [
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)",
"craft-image-codecs",
"image",
"log",
"proptest",
@@ -6982,7 +6926,7 @@ dependencies = [
name = "vectorcraft-metafile"
version = "0.24.1"
dependencies = [
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)",
"craft-image-codecs",
"craft-metafile",
"image",
"kurbo 0.13.1",
@@ -7023,10 +6967,10 @@ version = "0.24.1"
dependencies = [
"aes",
"chrono",
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)",
"craft-image-codecs",
"craft-pdf",
"craft-stream-codecs",
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)",
"craft-xml",
"flate2",
"getrandom 0.4.3",
"image",
@@ -7057,7 +7001,7 @@ dependencies = [
name = "vectorcraft-plugins"
version = "0.24.1"
dependencies = [
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)",
"craft-image-codecs",
"craft-vectorcraft-format",
"log",
"serde",
@@ -7077,10 +7021,10 @@ name = "vectorcraft-render"
version = "0.24.1"
dependencies = [
"craft-gif",
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)",
"craft-image-codecs",
"craft-psd",
"craft-stream-codecs",
"craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)",
"craft-tiff",
"flate2",
"image",
"jpeg-encoder",
@@ -7116,7 +7060,7 @@ name = "vectorcraft-svg"
version = "0.24.1"
dependencies = [
"craft-docpath",
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)",
"craft-image-codecs",
"craft-mime",
"craft-svg",
"data-url",
@@ -7146,7 +7090,7 @@ dependencies = [
name = "vectorcraft-testkit"
version = "0.24.1"
dependencies = [
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)",
"craft-image-codecs",
"fax",
"kurbo 0.13.1",
"proptest",
@@ -7164,6 +7108,7 @@ dependencies = [
name = "vectorcraft-text"
version = "0.24.1"
dependencies = [
"craft-proof",
"harfrust 0.13.3",
"icu_segmenter",
"kurbo 0.13.1",
@@ -7172,6 +7117,7 @@ dependencies = [
"subsetter",
"unicode-bidi",
"unicode-general-category",
"unicode-normalization",
"unicode-script",
"unicode-segmentation",
"vectorcraft-doc",
@@ -7194,7 +7140,7 @@ dependencies = [
name = "vectorcraft-tools"
version = "0.24.1"
dependencies = [
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)",
"craft-image-codecs",
"kurbo 0.13.1",
"serde",
"serde_json",
@@ -7211,7 +7157,7 @@ dependencies = [
name = "vectorcraft-trace"
version = "0.24.1"
dependencies = [
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)",
"craft-image-codecs",
"image",
"kurbo 0.13.1",
"serde",
@@ -7226,7 +7172,7 @@ version = "0.24.1"
dependencies = [
"bytemuck",
"chrono",
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)",
"craft-image-codecs",
"craft-keymap",
"craft-ui",
"craft-update",
+31 -31
View File
@@ -11,40 +11,40 @@ rust-version = "1.95"
repository = "https://github.com/storytold/vectorcraft"
[workspace.dependencies]
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e", default-features = false, features = ["interpret", "write"] }
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd", features = ["serde"] }
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b", default-features = false, features = ["interpret", "write"] }
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b", features = ["serde"] }
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
# Decides who draws the window frame (desktop vs. app) so the suite shares one native titlebar per
# desktop. The `egui` feature adds `craft_window::decorate`. (craft-libs#217.)
craft-window = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd", features = ["egui"] }
craft-window = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b", features = ["egui"] }
# The `.vectorcraft` envelope: its members, version, embedded images and the data after the JSON.
craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
# craft-update: app-specific pretend versions apply to startup and manual checks.
# Native Affinity documents (craft-libs#914).
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
# SVG parsing, limits, SVGZ and writer (craft-libs#778).
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "431f704478962677ec47e512754464d372901830", features = ["tree"] }
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b", features = ["tree"] }
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
# EPS container, previews, ASCII85 and DSC comments (craft-libs#778).
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
# DXF tags, reader and writer (craft-libs#778, #926, #927).
craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "a7fb55eaf9a15c21e8ce0b13cf605dc54fd15f57" }
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
# WMF, EMF and EMF+ reader (craft-libs#778).
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "a80c0f25f1c4767374a27a444fbf95e3e8162e14", default-features = false, features = ["write"] }
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" }
craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd", features = ["egui"] }
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b", default-features = false, features = ["write"] }
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b", features = ["egui"] }
# internal
vectorcraft-geom = { path = "crates/geom" }
vectorcraft-color = { path = "crates/color" }
@@ -184,13 +184,13 @@ lto = "thin"
codegen-units = 1
[patch.crates-io]
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" }
krilla = { git = "https://github.com/storytold/craft-libs", rev = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" }
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" }
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
krilla = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
+1 -1
View File
@@ -17,7 +17,7 @@ path = "src/main.rs"
vectorcraft-engine = { workspace = true, features = ["bundled-fonts", "heif"] }
vectorcraft-ui-egui = { workspace = true }
# The page command API (storytold/craft-libs#413): the request plumbing behind window.vectorcraft.
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "fd5e2feff6ea25bed371a99cc732b3968d621505", version = "0.1.0" }
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b", version = "0.1.0" }
vectorcraft-format = { workspace = true }
vectorcraft-text = { workspace = true }
egui = { workspace = true }
+4 -4
View File
@@ -78,7 +78,7 @@ impl Monitor {
let scale = self.scale * zoom;
let [x, y] = self.pos;
let [w, h] = self.size;
DockMonitor { name, rect: [x, y, w, h].map(|v| v as f32 / scale), scale }
DockMonitor { name, rect: [x, y, w, h].map(|v| v as f32 / scale), scale, work_area: None }
}
}
@@ -248,13 +248,13 @@ mod tests {
fn floating_panels_get_monitors_in_the_points_a_window_on_them_reports() {
let dock = |m: Monitor, zoom| m.docking(Some("m".into()), zoom);
let plain = dock(monitor(1920, 0, 1920, 1080, 1.0), 1.0);
assert_eq!(plain, DockMonitor { name: Some("m".into()), rect: [1920.0, 0.0, 1920.0, 1080.0], scale: 1.0 });
assert_eq!(plain, DockMonitor { name: Some("m".into()), rect: [1920.0, 0.0, 1920.0, 1080.0], scale: 1.0, work_area: None });
// A window at (3000, 200) on this monitor reports (1500, 100).
let scaled = dock(monitor(1920, -200, 3840, 2160, 2.0), 1.0);
assert_eq!(scaled, DockMonitor { name: Some("m".into()), rect: [960.0, -100.0, 1920.0, 1080.0], scale: 2.0 });
assert_eq!(scaled, DockMonitor { name: Some("m".into()), rect: [960.0, -100.0, 1920.0, 1080.0], scale: 2.0, work_area: None });
// The UI zoom divides what egui reports as well.
let zoomed = dock(monitor(-2560, 0, 2560, 1440, 1.0), 1.25);
assert_eq!(zoomed, DockMonitor { name: Some("m".into()), rect: [-2048.0, 0.0, 2048.0, 1152.0], scale: 1.25 });
assert_eq!(zoomed, DockMonitor { name: Some("m".into()), rect: [-2048.0, 0.0, 2048.0, 1152.0], scale: 1.25, work_area: None });
}
#[test]
+2
View File
@@ -11,6 +11,8 @@ workspace = true
[features]
# `vectorcraft_doc::blend::spines_built` for other crates' tests (dev-dependencies only).
spine-count = []
# `vectorcraft_doc::symbols_read` for other crates' tests (dev-dependencies only).
symbol-read-count = []
[dependencies]
vectorcraft-geom = { workspace = true }
+3
View File
@@ -75,6 +75,9 @@ pub mod style_libs;
pub mod swatches;
mod symbols;
pub use symbols::SymbolBoxes;
#[cfg(any(test, feature = "symbol-read-count"))]
#[doc(hidden)]
pub use symbols::symbols_read;
pub mod text;
pub mod trace;
pub mod twist;
+60 -13
View File
@@ -183,23 +183,69 @@ impl Selection {
self.key_anchor = None;
}
}
/// [`Self::add`] for each of `ids` in order, going through the selected objects once.
pub fn add_all(&mut self, ids: impl IntoIterator<Item = NodeId>) {
self.each(ids, false);
}
/// [`Self::toggle`] for each of `ids` in order, going through the selected objects once. An id
/// listed twice is removed and then added again at the end.
pub fn toggle_all(&mut self, ids: impl IntoIterator<Item = NodeId>) {
self.each(ids, true);
}
/// [`Self::add_all`], or [`Self::toggle_all`] when `toggle` is set. Each selected object slot
/// carries the number of the activation that made it; an id's slots are kept only when they
/// carry its current activation, so a removal drops every slot of the id at once.
fn each(&mut self, ids: impl IntoIterator<Item = NodeId>, toggle: bool) {
use std::collections::hash_map::{Entry, HashMap};
let mut ids = ids.into_iter().peekable();
if ids.peek().is_none() {
return;
}
self.target = None;
self.slices.clear();
self.symbol_part = None;
self.on_path_member = None;
let mut live: HashMap<NodeId, usize> = self.objects.iter().map(|id| (*id, 0)).collect();
let mut added: Vec<(NodeId, usize)> = Vec::new();
let mut removed = false;
for id in ids {
match live.entry(id) {
Entry::Vacant(e) => {
let activation = added.len() + 1;
e.insert(activation);
added.push((id, activation));
}
Entry::Occupied(e) if toggle => {
e.remove();
removed = true;
self.anchors.remove(&id);
self.segments.remove(&id);
if self.key == Some(id) {
self.key = None;
}
if self.key_anchor.is_some_and(|(k, _)| k == id) {
self.key_anchor = None;
}
}
Entry::Occupied(_) => {}
}
}
if removed {
self.objects.retain(|id| live.get(id) == Some(&0));
}
self.objects.extend(added.into_iter().filter(|(id, n)| live.get(id) == Some(n)).map(|(id, _)| id));
}
/// Select slices `ids` (see [`Selection::slices`]) and nothing else.
pub fn set_slices(&mut self, ids: impl IntoIterator<Item = NodeId>) {
self.clear();
for id in ids {
if !self.slices.contains(&id) {
self.slices.push(id);
}
}
let mut seen = HashSet::new();
self.slices.extend(ids.into_iter().filter(|id| seen.insert(*id)));
}
/// Select ruler guides `ids` (see [`Selection::guides`]) and nothing else.
pub fn set_guides(&mut self, ids: impl IntoIterator<Item = NodeId>) {
self.clear();
for i in ids {
if !self.guides.contains(&i) {
self.guides.push(i);
}
}
let mut seen = HashSet::new();
self.guides.extend(ids.into_iter().filter(|id| seen.insert(*id)));
}
/// Add ruler guide `i` to the selection, or take it out, keeping the selected objects (a
/// Shift-click on a guide).
@@ -426,10 +472,11 @@ impl Selection {
};
let locks = doc.locked_artboards();
ids.retain(|i| !locks.holds_id(*i));
if ids.iter().all(|i| self.contains(*i)) {
ids.iter().for_each(|i| self.remove(*i));
let selected: HashSet<NodeId> = self.objects.iter().copied().collect();
if ids.iter().all(|i| selected.contains(i)) {
self.remove_all(ids);
} else {
ids.into_iter().for_each(|i| self.add(i));
self.add_all(ids);
}
self.target = None;
}
+142
View File
@@ -45,6 +45,148 @@ fn remove_all_does_what_removing_each_does() {
assert_eq!(none, s);
}
/// A selection with every field set: objects 1 to 6 with 3 listed twice, anchors, segments, a key,
/// a key anchor, a target, slices, guides, a key guide, new art, a symbol part and an on-path member.
fn seeded() -> Selection {
let mut s = Selection { objects: [1, 2, 3, 4, 5, 3, 6].map(NodeId).to_vec(), ..Selection::default() };
for i in [2, 3, 4, 5] {
s.anchors.insert(NodeId(i), BTreeSet::from([(0, 1)]));
s.segments.insert(NodeId(i), BTreeSet::from([(0, 0)]));
}
s.key = Some(NodeId(4));
s.key_anchor = Some((NodeId(5), (0, 1)));
s.target = Some(NodeId(3));
s.slices = vec![NodeId(9)];
s.guides = vec![NodeId(10)];
s.key_guide = Some(NodeId(10));
s.new_art = Arc::new(HashSet::from([NodeId(2)]));
s.symbol_part = Some(SymbolPart { instance: NodeId(1), path: vec![0] });
s.on_path_member = Some(NodeId(11));
s
}
/// Id lists with repeats, ids not selected, removals followed by additions, and the empty list.
fn id_streams() -> Vec<Vec<NodeId>> {
let mut streams: Vec<Vec<NodeId>> = [
vec![],
vec![4],
vec![7],
vec![3],
vec![4, 1, 4, 7],
vec![7, 8, 7, 7, 3, 3, 5],
vec![1, 2, 3, 4, 5, 6],
vec![6, 5, 4, 3, 2, 1, 1, 2, 3],
vec![8, 2, 8, 2, 9, 9, 9],
]
.into_iter()
.map(|ids| ids.into_iter().map(NodeId).collect())
.collect();
// Deterministic pseudo-random lists over ids 1 to 12, half of them selected to start with.
let mut x: u64 = 0x9e37_79b9_7f4a_7c15;
for len in [5, 17, 40, 120] {
let ids = (0..len)
.map(|_| {
x ^= x << 13;
x ^= x >> 7;
x ^= x << 17;
NodeId(x % 12 + 1)
})
.collect();
streams.push(ids);
}
streams
}
#[test]
fn add_all_does_what_adding_each_does() {
for ids in id_streams() {
let mut one_by_one = seeded();
for id in &ids {
one_by_one.add(*id);
}
let mut all = seeded();
all.add_all(ids.iter().copied());
assert_eq!(all, one_by_one, "add_all({ids:?})");
}
}
#[test]
fn toggle_all_does_what_toggling_each_does() {
for ids in id_streams() {
let mut one_by_one = seeded();
for id in &ids {
one_by_one.toggle(*id);
}
let mut all = seeded();
all.toggle_all(ids.iter().copied());
assert_eq!(all, one_by_one, "toggle_all({ids:?})");
}
// An id toggled twice is selected again, at the end, without the anchors it had.
let mut s = seeded();
s.toggle_all([NodeId(2), NodeId(2)]);
assert_eq!(s.objects, [1, 3, 4, 5, 3, 6, 2].map(NodeId));
assert!(!s.anchors.contains_key(&NodeId(2)) && !s.segments.contains_key(&NodeId(2)));
// A removed key and key anchor stay cleared.
let mut s = seeded();
s.toggle_all([NodeId(4), NodeId(5), NodeId(4), NodeId(5)]);
assert_eq!((s.key, s.key_anchor), (None, None));
}
#[test]
fn set_slices_and_set_guides_keep_the_first_of_each_id() {
let mut s = seeded();
s.set_slices([3, 1, 3, 2, 1].map(NodeId));
assert_eq!(s.slices, [3, 1, 2].map(NodeId));
assert!(s.objects.is_empty() && s.guides.is_empty());
s.set_guides([5, 5, 4, 6, 4].map(NodeId));
assert_eq!(s.guides, [5, 4, 6].map(NodeId));
assert!(s.slices.is_empty());
}
/// Shift-clicking a target circle does what removing or adding each of its art one by one does,
/// for a layer with art, an empty layer and an object.
#[test]
fn toggle_target_does_what_toggling_its_art_one_by_one_does() {
let rect = || vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, 10.0, 10.0));
let mut d = Document::new(100.0, 100.0);
let l = d.layers[0].id;
let art: Vec<NodeId> = (0..4).map(|_| d.alloc_id()).collect();
for id in &art {
d.insert(Some(l), usize::MAX, Node::path(*id, rect(), crate::Appearance::default_art())).unwrap();
}
let empty = d.alloc_id();
d.insert(None, usize::MAX, Node::layer(empty, "Empty", crate::LayerColor::Preset(2))).unwrap();
let one_by_one = |s: &Selection, id: NodeId| {
let mut s = s.clone();
let ids = match d.node(id) {
Some(n) if n.is_layer() => n.layer_art(true),
_ => vec![id],
};
if ids.iter().all(|i| s.contains(*i)) {
ids.iter().for_each(|i| s.remove(*i));
} else {
ids.into_iter().for_each(|i| s.add(i));
}
s.target = None;
s
};
let mut starts = vec![Selection::default()];
for objects in [vec![art[1]], vec![art[3], art[0], art[1], art[2]], vec![art[2], art[2], NodeId(99)]] {
let mut s = seeded();
s.objects = objects;
s.key = s.objects.first().copied();
s.anchors.insert(art[1], BTreeSet::from([(0, 0)]));
starts.push(s);
}
for start in &starts {
for id in [l, empty, art[2], NodeId(99)] {
let mut s = start.clone();
s.toggle_target(&d, id);
assert_eq!(s, one_by_one(start, id), "toggle_target({id:?}) on {:?}", start.objects);
}
}
}
#[test]
fn remove_all_does_what_removing_each_does_to_a_key_anchor_and_symbol_part() {
for kept in [false, true] {
+83 -8
View File
@@ -9,7 +9,7 @@ use std::sync::Arc;
use vectorcraft_geom::{Affine, Rect};
use crate::symbol_nine_slice::transformed;
use crate::{AppearanceItem, Document, MAX_SYMBOL_NODES, NineSliceMap, Node, NodeKind, SYMBOL_HALF};
use crate::{AppearanceItem, Document, MAX_SYMBOL_NODES, NineSliceMap, Node, NodeKind, SYMBOL_HALF, Symbol};
/// The box a symbol instance is measured by when its symbol's art has no box
/// ([`SymbolBoxes::art`]), and in [`Node::geometric_bounds`]: the 20 × 20 square around the origin
@@ -312,7 +312,7 @@ impl Document {
/// Each symbol name of this document → the index of the first symbol of that name (the one a
/// name finds).
pub(crate) fn symbol_names(&self) -> SymbolNames {
#[cfg(test)]
#[cfg(any(test, feature = "symbol-read-count"))]
SYMBOLS_READ.with(|c| c.set(c.get() + self.symbols.len()));
let mut names = HashMap::with_capacity(self.symbols.len());
for (i, s) in self.symbols.iter().enumerate() {
@@ -322,7 +322,7 @@ impl Document {
}
}
#[cfg(test)]
#[cfg(any(test, feature = "symbol-read-count"))]
thread_local! {
/// How many symbols [`Document::symbol_names`] has read on this thread.
pub(crate) static SYMBOLS_READ: Cell<usize> = const { Cell::new(0) };
@@ -330,12 +330,31 @@ thread_local! {
static ART_BOXES_MEASURED: Cell<usize> = const { Cell::new(0) };
}
/// How many symbols [`Document::symbol_names`] has read on this thread, for other crates' tests
/// that count how often the symbol list is read to find symbols by name (the `symbol-read-count`
/// feature, dev-dependencies only).
#[cfg(any(test, feature = "symbol-read-count"))]
#[doc(hidden)]
pub fn symbols_read() -> usize {
SYMBOLS_READ.with(Cell::get)
}
impl<'a> SymbolBoxes<'a> {
/// The document whose symbols these are.
pub fn document(&self) -> &'a Document {
self.doc
}
/// New boxes for the same document, none measured yet and with none of the options set, that
/// find symbols by name through the same index as these boxes ([`Self::symbol`]). Measuring
/// objects one at a time in boxes of their own made this way measures them as boxes made by
/// [`Document::symbol_boxes`] do, without reading the symbol list again.
pub fn unmeasured(&self) -> SymbolBoxes<'a> {
let doc: &'a Document = self.doc;
let names = self.names.get_or_init(|| Arc::new(doc.symbol_names()));
doc.symbol_boxes().with_names(names)
}
/// Makes these boxes find symbols by `names` ([`Document::symbol_names`]), made from the
/// document's symbols while they had the names and order they have now.
pub(crate) fn with_names(self, names: &Arc<SymbolNames>) -> Self {
@@ -343,19 +362,24 @@ impl<'a> SymbolBoxes<'a> {
self
}
/// The art of the first symbol of the document named `name`, found in time independent of the
/// number of symbols after the first lookup.
pub(crate) fn symbol_art(&self, name: &str) -> Option<&'a Arc<Node>> {
/// The first symbol of the document named `name`, found in time independent of the number of
/// symbols after the first lookup.
pub fn symbol(&self, name: &str) -> Option<&'a Symbol> {
let doc: &'a Document = self.doc;
let names = self.names.get_or_init(|| Arc::new(doc.symbol_names()));
let i = *names.get(name)?;
match doc.symbols.get(i) {
Some(s) if s.name == name => Some(&s.art),
Some(s) if s.name == name => Some(s),
// Names that no longer match the symbols: the first symbol of that name.
_ => doc.symbols.iter().find(|s| s.name == name).map(|s| &s.art),
_ => doc.symbols.iter().find(|s| s.name == name),
}
}
/// The art of the first symbol of the document named `name` ([`Self::symbol`]).
pub(crate) fn symbol_art(&self, name: &str) -> Option<&'a Arc<Node>> {
self.symbol(name).map(|s| &s.art)
}
/// Makes these boxes measure every symbol instance as [`Node::reach_bounds_with`] does, by its
/// art box alone. An instance that scales or turns stroked art then measures a little larger
/// than with [`Node::visual_bounds_with`], and its art is not transformed to measure it. The
@@ -904,6 +928,57 @@ mod tests {
assert_eq!(s.sliced_placed.get(), 13);
}
#[test]
fn symbols_are_found_by_name_reading_the_list_once() {
// 2,000 symbols, then two named "Mark": a name finds the first.
let mut d = Document::new(200.0, 200.0);
for i in 0..2000 {
let r = rect(&mut d, Rect::new(0.0, 0.0, 1.0, 1.0), 0.0);
symbol(&mut d, &format!("Filler {i}"), vec![r]);
}
let (first, second) = (rect(&mut d, Rect::new(0.0, 0.0, 10.0, 10.0), 0.0), rect(&mut d, Rect::new(0.0, 0.0, 20.0, 20.0), 0.0));
symbol(&mut d, "Mark", vec![first]);
symbol(&mut d, "Mark", vec![second]);
let read = || SYMBOLS_READ.with(Cell::get);
let before = read();
let s = d.symbol_boxes();
for _ in 0..1000 {
assert!(s.symbol("Mark").is_some_and(|m| std::ptr::eq(m, &d.symbols[2000])));
assert!(s.symbol("Filler 7").is_some_and(|m| std::ptr::eq(m, &d.symbols[7])));
assert!(s.symbol("Nowhere").is_none());
}
assert_eq!(read() - before, d.symbols.len());
}
#[test]
fn unmeasured_boxes_share_the_index_and_nothing_measured() {
// 2,000 symbols, then a 9-slice frame held, scaled, by "Holder", whose instances spend
// the boxes' budget of placed objects.
let mut d = Document::new(200.0, 200.0);
for i in 0..2000 {
let r = rect(&mut d, Rect::new(0.0, 0.0, 1.0, 1.0), 0.0);
symbol(&mut d, &format!("Filler {i}"), vec![r]);
}
let frame = rect(&mut d, Rect::new(0.0, 0.0, 100.0, 100.0), 1.0);
symbol(&mut d, "Panel", vec![frame]);
d.set_symbol_nine_slice("Panel", Some(crate::SymbolNineSlice::default()));
let wide = instance(&mut d, "Panel", Affine::scale_non_uniform(2.0, 1.0));
symbol(&mut d, "Holder", vec![wide]);
let holder = instance(&mut d, "Holder", Affine::scale_non_uniform(1.5, 1.5));
let fresh = holder.visual_bounds_with(&d.symbol_boxes().quick());
let read = || SYMBOLS_READ.with(Cell::get);
let s = d.symbol_boxes().quick();
assert_eq!(holder.visual_bounds_with(&s), fresh);
assert!(s.sliced_placed.get() > 0);
let before = read();
let u = s.unmeasured();
assert_eq!(read(), before, "the index is shared");
assert!(u.measured.borrow().is_empty() && u.sliced.borrow().is_empty() && u.reaches.borrow().is_empty());
assert_eq!((u.sliced_placed.get(), u.holders.get(), u.quick.get()), (0, 0, false));
assert_eq!(holder.visual_bounds_with(&u.quick()), fresh);
assert_eq!(read(), before);
}
#[test]
fn measuring_9_slice_instances_reads_the_symbol_list_once() {
// 2,000 symbols, then a frame with guides and a symbol with guides holding the frame
+7 -7
View File
@@ -94,13 +94,13 @@ pub use revolve::{
CLASSIC_REVOLVE, REVOLVE, has_revolve, is_revolve, revolve_art, revolve_art_in, revolve_options, validate_revolve, validate_revolve_in,
};
pub use solids::{
CLASSIC_EXTRUDE, CLASSIC_ROTATE, EXTRUDE, GRAPHICS, GraphicFrame, INFLATE, MAX_GRAPHICS, MappedGraphic, RENDER, RENDER_MODES, ROTATE,
ROTATE_SURFACES, ROTATION_PRESETS, SHADING_COLORS, SOLIDS, SolidMesh, THREE_D_TYPES, classic_extrude_options, classic_shading, extrude_options,
graphic_bounds, graphic_frame, graphic_symbols, has_solid, inflate_options, is_classic_three_d, is_three_d, mapped_graphics, missing_symbol,
names_graphic_symbol, rename_graphic_symbol, rename_graphic_symbol_in, renders_wireframe, solid_art, solid_art_in, takes_graphics,
three_d_meshes, three_d_meshes_in, three_d_meshes_of, three_d_meshes_of_in, three_d_params_as, three_d_wireframe_in, validate_solid,
validate_solid_in, validate_three_d, validate_three_d_at, validate_three_d_at_in, validate_three_d_in, validate_three_d_params, view_options,
with_graphic,
CLASSIC_EXTRUDE, CLASSIC_ROTATE, EXTRUDE, GRAPHICS, GraphicFrame, INFLATE, MAX_GRAPHICS, MappedGraphic, MeshGraphics, RENDER, RENDER_MODES,
ROTATE, ROTATE_SURFACES, ROTATION_PRESETS, SHADING_COLORS, SOLIDS, SolidMesh, THREE_D_TYPES, classic_extrude_options, classic_shading,
extrude_options, graphic_bounds, graphic_frame, graphic_symbols, has_solid, inflate_options, is_classic_three_d, is_three_d, mapped_graphics,
mesh_graphics_art, missing_symbol, names_graphic_symbol, rename_graphic_symbol, rename_graphic_symbol_in, renders_wireframe, solid_art,
solid_art_in, takes_graphics, three_d_meshes, three_d_meshes_in, three_d_meshes_of, three_d_meshes_of_in, three_d_params_as,
three_d_wireframe_in, validate_solid, validate_solid_in, validate_three_d, validate_three_d_at, validate_three_d_at_in, validate_three_d_in,
validate_three_d_params, view_options, with_graphic,
};
pub use solids::{
GRAPHIC_MAX_OFFSET, GRAPHIC_SCALE_RANGE, GRAPHICS_NOT_TAKEN, appearance_graphic_symbols, exports_three_d, graphic_frame_at,
+2 -2
View File
@@ -801,7 +801,7 @@ pub(crate) fn revolve_meshes(n: &Node, total: &mut usize, limit: usize) -> Resul
let b = path.bounds().ok_or("Revolve requires a shape with at least two anchors")?;
let (paint, opacity, _) = paint_of(item);
let mesh = vectorcraft_three_d::revolve_mesh(path, rule, b, fx_options(fx))?;
Ok(crate::SolidMesh { mesh, color: crate::solids::mesh_color(&paint, opacity) })
Ok(crate::SolidMesh::plain(mesh, crate::solids::mesh_color(&paint, opacity)))
};
if let Some(index) = n.appearance.effects.iter().position(|e| e.visible && is_revolve(&e.id)) {
let before = n.appearance.effects.get(..index).unwrap_or_default();
@@ -924,7 +924,7 @@ fn group_meshes(n: &Node, total: &mut usize, limit: usize) -> Result<Vec<crate::
let Some(item) = surface_item(&s.items) else { continue };
let (paint, opacity, _) = paint_of(item);
let mesh = vectorcraft_three_d::revolve_mesh(&s.path, s.rule, b, options)?;
crate::solids::keep_mesh(&mut out, total, crate::SolidMesh { mesh, color: crate::solids::mesh_color(&paint, opacity * s.opacity) }, limit)?;
crate::solids::keep_mesh(&mut out, total, crate::SolidMesh::plain(mesh, crate::solids::mesh_color(&paint, opacity * s.opacity)), limit)?;
}
Ok(out)
}
+78 -5
View File
@@ -25,8 +25,8 @@ pub(crate) use source::{resolve, resolve_for};
pub(crate) mod graphics;
pub use graphics::{
GRAPHICS, GraphicFrame, MAX_GRAPHICS, MappedGraphic, graphic_symbols, mapped_graphics, missing_symbol, names_graphic_symbol,
rename_graphic_symbol, rename_graphic_symbol_in, takes_graphics, with_graphic,
GRAPHICS, GraphicFrame, MAX_GRAPHICS, MappedGraphic, MeshGraphics, graphic_symbols, mapped_graphics, mesh_graphics_art, missing_symbol,
names_graphic_symbol, rename_graphic_symbol, rename_graphic_symbol_in, takes_graphics, with_graphic,
};
pub use graphics::{
MAX_OFFSET as GRAPHIC_MAX_OFFSET, NOT_TAKEN as GRAPHICS_NOT_TAKEN, SCALE_RANGE as GRAPHIC_SCALE_RANGE, appearance_graphic_symbols,
@@ -2322,6 +2322,71 @@ pub struct SolidMesh {
/// The paint's display color (sRGB, 0..1) and its opacity: a gradient's stops averaged, gray
/// for a pattern.
pub color: [f32; 4],
/// The graphics mapped onto the mesh when it is the part of a solid's planar face that carries
/// some ([`split_graphics`]); `None` otherwise.
pub graphics: Option<MeshGraphics>,
}
impl SolidMesh {
/// A mesh painted `color`, with no graphics.
pub fn plain(mesh: Mesh, color: [f32; 4]) -> Self {
Self { mesh, color, graphics: None }
}
}
/// The parts of `mesh`, a solid that 3D effect `id` with parameters `p` built about `bounds`, painted
/// `color` from a fill or stroke at `opacity`: for each planar face that carries graphics (Extrude &
/// Bevel's caps, the plane), the triangles on it as a mesh of their own with the art point of each
/// corner ([`MeshGraphics`]), then the rest. Revolve's side, whose graphics are not mapped onto its
/// mesh, stays plain.
fn split_graphics(id: &str, p: &Value, bounds: Rect, mesh: Mesh, (color, opacity): ([f32; 4], f32)) -> Vec<SolidMesh> {
let list = graphics::mapped_graphics(p);
if list.is_empty() || !takes_graphics(id) || id == crate::REVOLVE {
return vec![SolidMesh::plain(mesh, color)];
}
let view = view_options(p);
let mut rest = mesh;
let mut out = vec![];
for face in PlanarFace::ALL {
if !list.iter().any(|g| g.face == face) {
continue;
}
let on_mesh = if id == ROTATE {
vectorcraft_three_d::plane_mesh_face(bounds, view)
} else {
vectorcraft_three_d::extrude_mesh_face(bounds, extrude_options(p), view, face)
};
let Some(on_mesh) = on_mesh else { continue };
let (mut taken, mut left, mut art) = (Mesh::default(), Mesh::default(), vec![]);
for t in &rest.triangles {
let corner = |i: u32| rest.positions.get(i as usize).copied().zip(rest.normals.get(i as usize).copied());
let Some(corners) = t.iter().map(|&i| corner(i)).collect::<Option<Vec<_>>>() else { continue };
let points: Option<Vec<Point>> = corners.iter().map(|(m, n)| on_mesh.art_point(*m, *n)).collect();
let into = match points {
Some(points) => {
art.extend(points);
&mut taken
}
None => &mut left,
};
let base = into.positions.len() as u32;
for (m, n) in corners {
into.positions.push(m);
into.normals.push(n);
}
into.triangles.push([base, base + 1, base + 2]);
}
rest = left;
if !taken.is_empty() {
let graphics = list.iter().filter(|g| g.face == face).cloned().collect();
let graphics = MeshGraphics { face, graphics, center: bounds.center(), art, opacity, object: 1.0 };
out.push(SolidMesh { mesh: taken, color, graphics: Some(graphics) });
}
}
if !rest.is_empty() {
out.insert(0, SolidMesh::plain(rest, color));
}
out
}
/// The color a mesh of `paint` at `opacity` takes ([`SolidMesh::color`]).
@@ -2363,13 +2428,18 @@ fn meshes_for(fx: &Effect, shapes: &[Profile], total: &mut usize, limit: usize)
let p = crate::merged_params(&fx.id, &fx.params);
let view = view_options(&p);
let mut out = vec![];
let mut keep = |out: &mut Vec<SolidMesh>, mesh: Mesh, color: [f32; 4]| keep_mesh(out, total, SolidMesh { mesh, color }, limit);
// A solid's parts with and without graphics count together against the limit.
let mut keep = |out: &mut Vec<SolidMesh>, mesh: Mesh, (paint, opacity): (&Paint, f32), bounds: Rect| {
split_graphics(&fx.id, &p, bounds, mesh, (mesh_color(paint, opacity), opacity))
.into_iter()
.try_for_each(|part| keep_mesh(out, total, part, limit))
};
if is_plane(&fx.id) {
for s in shapes {
for item in &s.items {
let (paint, opacity, _) = paint_of(item, s.opacity);
let (area, rule) = region(&s.path, s.rule, item);
keep(&mut out, vectorcraft_three_d::plane_mesh(&area, rule, b, view)?, mesh_color(&paint, opacity))?;
keep(&mut out, vectorcraft_three_d::plane_mesh(&area, rule, b, view)?, (&paint, opacity), b)?;
}
}
return Ok(out);
@@ -2406,7 +2476,7 @@ fn meshes_for(fx: &Effect, shapes: &[Profile], total: &mut usize, limit: usize)
match solid.mesh() {
Ok(mesh) => {
let (paint, opacity, _) = paint_of(item, *member);
keep(&mut out, mesh, mesh_color(&paint, opacity))?;
keep(&mut out, mesh, (&paint, opacity), bounds)?;
}
Err(_) if matches!(item, AppearanceItem::Stroke(_)) => {}
Err(e) => return Err(e),
@@ -2494,6 +2564,9 @@ fn meshes_within(doc: Option<&Document>, n: &Node, total: &mut usize, limit: usi
.filter(|m| !m.mesh.is_empty())
.map(|mut m| {
m.color[3] *= n.opacity.clamp(0.0, 1.0);
if let Some(g) = &mut m.graphics {
g.object *= n.opacity.clamp(0.0, 1.0);
}
m
})
.collect();
+65
View File
@@ -519,6 +519,71 @@ pub(super) fn face_art(
Some(Node::new(id, NodeKind::Group { children: vec![Arc::new(clip), Arc::new(Node::group(id, children))], clip: true }))
}
/// The graphics on one planar face of a solid's mesh ([`super::SolidMesh`]): those mapped onto
/// `face`, placed about `center` (the center of the bounds the solids were built with), and the
/// point of the art's plane that each corner of the mesh shows (document coordinates of the art
/// before its 3D effect, y down).
#[derive(Clone, Debug, PartialEq)]
pub struct MeshGraphics {
pub face: PlanarFace,
pub graphics: Vec<MappedGraphic>,
pub center: Point,
/// One for each position of the mesh.
pub art: Vec<Point>,
/// The opacity of the fill or stroke the face is painted with, which the graphics take too, as
/// the canvas draws them; neither a gradient's stops nor the object's own opacity is in it.
pub opacity: f32,
/// The opacity of the object the face belongs to, which applies to the face and its graphics
/// together.
pub object: f32,
}
impl MeshGraphics {
/// The bounds of the art points of the mesh's corners; `None` without corners.
pub fn art_bounds(&self) -> Option<Rect> {
let first = *self.art.first()?;
Some(self.art.iter().fold(Rect::from_points(first, first), |r, p| r.union_pt(*p)))
}
}
/// The art `graphics` draws on its face, flat in the art's plane, unshaded and unclipped: each
/// graphic's fills and stroke outlines at its place ([`MappedGraphic`]), back to front, as one
/// group of objects with id `id`. A graphic whose symbol `doc` does not have, or whose art is past
/// the limits of [`pieces_of`], is left out, as the canvas leaves it out. `Ok(None)` when nothing
/// is drawn; an error when the graphics' art draws more than [`MAX_ELEMENTS`] path elements
/// together.
pub fn mesh_graphics_art(doc: &Document, id: NodeId, graphics: &MeshGraphics) -> Result<Option<Node>, String> {
let mut children = vec![];
let mut elements = 0usize;
for g in graphics.graphics.iter().filter(|g| g.face == graphics.face) {
let Some(symbol) = doc.symbols.iter().find(|s| s.name == g.symbol) else { continue };
let Ok(pieces) = pieces_of(doc, symbol) else { continue };
let Some(bounds) = pieces.iter().filter_map(|p| p.path.bounds()).reduce(|a, b| a.union(b)) else { continue };
let place = g.placement(bounds, graphics.center);
for piece in pieces {
elements = elements.saturating_add(drawn_elements(&piece.path, 1));
if elements > MAX_ELEMENTS {
return Err("The graphics are too complex: simplify the symbols' art".into());
}
let mut paint = piece.paint;
if let Paint::Pattern { xf, .. } = &mut paint {
*xf = place * *xf;
}
let mut fill = FillLayer::new(paint);
fill.opacity = piece.opacity;
fill.blend = piece.blend;
let mut appearance = Appearance { items: vec![AppearanceItem::Fill(fill)], ..Default::default() };
appearance.transform_gradients(place);
let mut node = Node::path(id, piece.path.transformed(place), appearance);
if let NodeKind::Path { rule, .. } = &mut node.kind {
*rule = piece.rule;
}
children.push(Arc::new(node));
}
}
Ok((!children.is_empty()).then(|| Node::group(id, children)))
}
/// One area of a graphic placed on Revolve's unrolled side surface, cut into straight pieces.
struct Unrolled {
polygons: Vec<Vec<Point>>,
@@ -86,6 +86,48 @@ fn a_graphic_is_drawn_on_the_front_cap_at_its_offset_size_and_turn() {
assert!((b.width() - 10.0 * 2f64.sqrt()).abs() < 1e-6);
}
#[test]
fn a_mesh_carries_its_caps_graphics_flat_in_the_arts_plane() {
let d = document();
let graphics =
json!([{"symbol": "Mark", "x": 20.0, "y": -10.0, "scale": 200.0}, {"symbol": "Mark", "face": "back", "x": 20.0, "y": -10.0, "scale": 200.0}]);
// Turned, so the caps' corners in the mesh are not the art's.
let n = object(EXTRUDE, json!({"rotationX": -20.0, "rotationY": 35.0, "rotationZ": 10.0, "graphics": graphics}));
let parts = super::super::three_d_meshes_in(Some(&d), &n).unwrap();
// The walls first, then the front cap and the back cap, each two triangles.
assert_eq!(
parts.iter().map(|p| p.graphics.as_ref().map(|g| g.face)).collect::<Vec<_>>(),
[None, Some(PlanarFace::Front), Some(PlanarFace::Back)]
);
let total: usize = parts.iter().map(|p| p.mesh.triangles.len()).sum();
let plain = super::super::three_d_meshes_in(Some(&d), &object(EXTRUDE, json!({"rotationX": -20.0, "rotationY": 35.0, "rotationZ": 10.0})));
assert_eq!(total, plain.as_ref().map_or(0, |p| p.iter().map(|p| p.mesh.triangles.len()).sum()), "no triangle is lost or doubled");
assert!(plain.unwrap().iter().all(|p| p.graphics.is_none()));
// The art points of each cap's corners are the art's own square; the graphic is drawn flat at
// its place, mirrored on the back so it reads from behind.
for (part, drawn) in parts[1..].iter().zip([Rect::new(60.0, 30.0, 80.0, 50.0), Rect::new(20.0, 30.0, 40.0, 50.0)]) {
let Some(g) = &part.graphics else { panic!("no graphics") };
assert_eq!(g.art.len(), part.mesh.positions.len());
assert!(close(g.art_bounds().unwrap(), Rect::new(0.0, 0.0, 100.0, 100.0)), "{:?}", g.art_bounds());
assert_eq!(g.graphics.len(), 1);
let art = mesh_graphics_art(&d, NodeId(9), g).unwrap().unwrap();
let paths: Vec<(PathData, Paint)> = art
.children()
.into_iter()
.flatten()
.filter_map(|c| Some((c.path_data()?.clone(), c.appearance.items.first()?.paint().clone())))
.collect();
assert!(close(bounds_of(&paths), drawn), "{:?}: {:?}", g.face, bounds_of(&paths));
assert_eq!(paths[0].1, Paint::solid(red()), "unshaded");
}
// A plane is all one face; a graphic whose symbol is gone draws nothing.
let n = object(ROTATE, json!({"rotationY": 35.0, "graphics": [{"symbol": "Gone"}]}));
let parts = super::super::three_d_meshes_in(Some(&d), &n).unwrap();
assert_eq!(parts.len(), 1);
let Some(g) = &parts[0].graphics else { panic!("no graphics") };
assert_eq!(mesh_graphics_art(&d, NodeId(9), g), Ok(None));
}
#[test]
fn without_the_document_or_its_symbol_nothing_is_drawn() {
let n = object(EXTRUDE, json!({"graphics": [{"symbol": "Mark"}]}));
@@ -563,6 +605,15 @@ fn art_nested_too_deep_is_refused_and_not_drawn() {
// A loaded file draws its other graphics.
let both = object(EXTRUDE, json!({"graphics": [{"symbol": "Deep"}, {"symbol": "Mark"}]}));
assert_eq!(graphics_in(&solid_art_in(Some(&d), &both).unwrap()).len(), 1);
// A mesh's graphics leave it out as well and draw the others.
let parts = super::super::three_d_meshes_in(Some(&d), &both).unwrap();
let Some(g) = parts.iter().find_map(|p| p.graphics.as_ref()) else { panic!("no graphics") };
let art = mesh_graphics_art(&d, NodeId(9), g).unwrap().unwrap();
assert_eq!(art.children().map_or(0, |c| c.len()), 1);
let deep = object(EXTRUDE, json!({"graphics": [{"symbol": "Deep"}]}));
let parts = super::super::three_d_meshes_in(Some(&d), &deep).unwrap();
let Some(g) = parts.iter().find_map(|p| p.graphics.as_ref()) else { panic!("no graphics") };
assert_eq!(mesh_graphics_art(&d, NodeId(9), g), Ok(None));
}
#[test]
+1 -1
View File
@@ -238,7 +238,7 @@ fn meshes_built_apart(fx: &Effect, shapes: &[Profile], total: &mut usize, limit:
match mesh {
Ok(mesh) => {
let (paint, opacity, _) = paint_of(item, *opacity);
keep_mesh(&mut out, total, SolidMesh { mesh, color: mesh_color(&paint, opacity) }, limit)?;
keep_mesh(&mut out, total, SolidMesh::plain(mesh, mesh_color(&paint, opacity)), limit)?;
}
Err(_) if matches!(item, AppearanceItem::Stroke(_)) => {}
Err(e) => return Err(e),
+3 -1
View File
@@ -47,6 +47,7 @@ vectorcraft-js = { workspace = true }
vectorcraft-apischema = { workspace = true }
image = { workspace = true }
craft-image-codecs = { workspace = true }
tiff = { workspace = true }
jxl-oxide = { workspace = true }
jxl-color = { workspace = true }
jxl-grid = { workspace = true }
@@ -88,7 +89,6 @@ craft-jxl = { workspace = true }
# vectorcraft-doc's Group 3 TIFF reader before craft-stream-codecs, the reference
# tests/group3_reference.rs compares it with.
hayro-ccitt = { workspace = true }
tiff = { workspace = true }
craft-stream-codecs = { workspace = true }
vectorcraft-affinity = { workspace = true, features = ["synth"] }
crc32fast = { workspace = true }
@@ -98,6 +98,8 @@ proptest = { workspace = true }
vectorcraft-text = { workspace = true, features = ["test-fonts"] }
# How many times an open reads a PDF.
vectorcraft-pdf = { workspace = true, features = ["read-count"] }
# How many times the symbol list is read to find symbols by name.
vectorcraft-doc = { workspace = true, features = ["symbol-read-count"] }
wat = { workspace = true }
# Zstandard streams for the Illustrator editing data fuzz tests.
ruzstd = { workspace = true }
+95
View File
@@ -0,0 +1,95 @@
//! `cargo run --release -p vectorcraft-engine --example selection_bench` prints the time of the
//! selection steps behind `select.toggle`, `select.add` and `select.inverse` on selections of 2,000,
//! 20,000 and 50,000 objects, done one id at a time (`old`) and in one pass (`new`), side by side in
//! one process. Each step checks that both give the same selection before it is timed.
//! `ITERS` sets the runs per step (default 7); each row is the median wall time in ms.
// Example (dev tool): unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness).
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use std::collections::HashSet;
use std::hint::black_box;
use std::time::Instant;
use vectorcraft_doc::{NodeId, Selection};
fn iters() -> usize {
std::env::var("ITERS").ok().and_then(|v| v.parse().ok()).unwrap_or(7).max(1)
}
fn median(mut ms: Vec<f64>) -> f64 {
ms.sort_by(f64::total_cmp);
ms[ms.len() / 2]
}
/// The median time of `old` and of `new` on clones of `start`, run in turn.
fn time(start: &Selection, old: impl Fn(&mut Selection), new: impl Fn(&mut Selection)) -> (f64, f64) {
let (mut a, mut b) = (start.clone(), start.clone());
old(&mut a);
new(&mut b);
assert_eq!(a, b, "both ways give the same selection");
let run = |f: &dyn Fn(&mut Selection)| {
let mut s = start.clone();
let t = Instant::now();
f(&mut s);
let ms = t.elapsed().as_secs_f64() * 1000.0;
black_box(s);
ms
};
let (mut olds, mut news) = (Vec::new(), Vec::new());
for _ in 0..iters() {
olds.push(run(&old));
news.push(run(&new));
}
(median(olds), median(news))
}
/// `select.add` before the change: [`Selection::add`] for each id.
fn old_add(s: &mut Selection, ids: &[NodeId]) {
for id in ids {
s.add(*id);
}
}
/// `select.toggle` before the change: [`Selection::toggle`] for each id.
fn old_toggle(s: &mut Selection, ids: &[NodeId]) {
for id in ids {
s.toggle(*id);
}
}
/// `select.inverse` before the change: the selectable ids not found by [`Selection::contains`].
fn old_inverse(s: &mut Selection, selectable: &[NodeId]) {
let ids: Vec<NodeId> = selectable.iter().copied().filter(|id| !s.contains(*id)).collect();
s.set(ids);
}
/// `select.inverse` after the change: the selectable ids not in a set of the selected ones.
fn new_inverse(s: &mut Selection, selectable: &[NodeId]) {
let selected: HashSet<NodeId> = s.objects.iter().copied().collect();
let ids: Vec<NodeId> = selectable.iter().copied().filter(|id| !selected.contains(id)).collect();
s.set(ids);
}
fn row(name: &str, (old, new): (f64, f64)) {
println!(" {name:<44} {old:>12.3} ms {new:>12.3} ms {:>9.1}x", old / new.max(1e-9));
}
fn main() {
println!(" {:<44} {:>15} {:>15} {:>10}", "step", "old", "new", "speedup");
for n in [2_000u64, 20_000, 50_000] {
println!("{n} objects");
let all: Vec<NodeId> = (1..=n).map(NodeId).collect();
let none = Selection::default();
let mut every = Selection::default();
every.set(all.iter().copied());
let mut half = Selection::default();
half.set(all.iter().copied().step_by(2));
let interleaved: Vec<NodeId> = all.iter().copied().skip(n as usize / 4).chain(all.iter().copied().take(n as usize / 4)).collect();
let half_new: Vec<NodeId> = all.iter().copied().skip(n as usize / 2).collect();
row("toggle every object off", time(&every, |s| old_toggle(s, &all), |s| s.toggle_all(all.iter().copied())));
row("toggle every object on", time(&none, |s| old_toggle(s, &all), |s| s.toggle_all(all.iter().copied())));
row("toggle every object, half selected", time(&half, |s| old_toggle(s, &interleaved), |s| s.toggle_all(interleaved.iter().copied())));
row("add half the objects, half selected", time(&half, |s| old_add(s, &half_new), |s| s.add_all(half_new.iter().copied())));
row("inverse, half selected", time(&half, |s| old_inverse(s, &all), |s| new_inverse(s, &all)));
}
}
+1 -1
View File
@@ -147,7 +147,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Add Points at Crossings",
["Object", "Plug-ins", "Path Precision Tools"],
None,
"{cut?: bool (false: add anchors where the paths cross; true: also cut them there), selfCrossings?: bool (false: where a path crosses itself too, a curved segment that loops over itself included), ids?: [id…] (default: the selection)} where the paths under the objects cross one another, as one undo step; at most 10000 segments → {ids, crossings (anchors placed)}",
"{cut?: bool (false: add anchors where the paths cross; true: also cut them there), selfCrossings?: bool (false: where a path crosses itself too, a curved segment that loops over itself included), ids?: [id…] (default: the selection)} where the paths under the objects cross one another, an open end that lies within 0.001 pt of another path counting as crossing it there, as one undo step; at most 10000 segments → {ids, crossings (anchors placed)}",
has_selection,
crossings
),
@@ -35,7 +35,7 @@ pub(super) fn specs() -> Vec<CommandSpec> {
"Trim at Crossings",
[],
None,
"{at: [x, y], tolerance?: pt 0..100 (3; how near `at` a path counts as under it)} or {rect: [x, y, width, height]} or {points: [[x, y]…] (2 to 100000 points)} remove stretches of paths, a stretch running between two neighboring places where the path is crossed by another path or by itself, or from such a place to an open end: `at` removes the stretch of the nearest path at that point, `rect` every stretch the rectangle touches, `points` every stretch the line through the points crosses. Give exactly one of the three. Every path that can be edited takes part, selected or not, compound path members included; hidden and locked paths, guides and clipping paths (compound ones' members included) are neither trimmed nor counted as crossing; in isolation mode only paths inside the isolated object are trimmed. A path that ends on another marks a place on the other; paths that lie along each other don't cross. A closed path that loses a stretch becomes open, an open path that loses a middle stretch becomes two paths with its appearance in its place in the stacking order, and a path nothing crosses is removed whole; a live shape becomes a plain path. One undo step, none when nothing is removed → {ids (the paths left of those trimmed), removed (stretches)}",
"{at: [x, y], tolerance?: pt 0..100 (3; how near `at` a path counts as under it)} or {rect: [x, y, width, height]} or {points: [[x, y]…] (2 to 100000 points)} remove stretches of paths, a stretch running between two neighboring places where the path is crossed by another path or by itself, or from such a place to an open end: `at` removes the stretch of the nearest path at that point, `rect` every stretch the rectangle touches, `points` every stretch the line through the points crosses. Give exactly one of the three. Every path that can be edited takes part, selected or not, compound path members included; hidden and locked paths, guides and clipping paths (compound ones' members included) are neither trimmed nor counted as crossing; in isolation mode only paths inside the isolated object are trimmed. A path that ends on another, or within 0.001 pt of it, marks a place on the other; paths that lie along each other don't cross. A closed path that loses a stretch becomes open, an open path that loses a middle stretch becomes two paths with its appearance in its place in the stacking order, and a path nothing crosses is removed whole; a live shape becomes a plain path. One undo step, none when nothing is removed → {ids (the paths left of those trimmed), removed (stretches)}",
has_doc,
trim
)]
@@ -782,3 +782,45 @@ fn bad_params_are_refused_and_change_nothing() {
assert_eq!(steps(&s), n);
assert!(*s.doc().unwrap().doc == *before);
}
#[test]
fn a_line_ending_on_a_curve_that_was_cut_still_divides_it_there() {
// An open egg-shaped curve, lines across it whose stubs on the left are trimmed away, so each
// line ends on the curve, and the curve's bottom trimmed off below the last line, which cuts
// its segments there. A click on the curve between the last two lines removes only that
// stretch: the lines' ends on it still divide it, however the curve was cut. Twenty placements,
// as how near a cut end lies to the curve depends on the coordinates.
for shift in 0..20 {
let dx = shift as f64 * 7.31;
let mut s = session();
let egg = json!({"anchors": [
{"x": 160.0 + dx, "y": 40.0, "out": [110.0 + dx, 80.0]},
{"x": 92.3 + dx, "y": 190.7, "in": [88.0 + dx, 140.0], "out": [97.0 + dx, 240.0]},
{"x": 170.0 + dx, "y": 268.0, "in": [130.0 + dx, 265.0], "out": [210.0 + dx, 271.0]},
{"x": 236.4 + dx, "y": 170.2, "in": [238.0 + dx, 230.0], "out": [233.0 + dx, 110.0]},
{"x": 150.0 + dx, "y": 20.0, "in": [200.0 + dx, 40.0]}
], "closed": false});
let egg = NodeId(s.execute("path.create", &egg).unwrap()["id"].as_u64().unwrap());
s.execute("select.none", &json!({})).unwrap();
let ys: Vec<f64> = (0..8).map(|k| 70.0 + k as f64 * 23.17 + shift as f64 * 0.37).collect();
let lines: Vec<NodeId> = ys.iter().map(|y| line(&mut s, &[(40.0 + dx, *y), (300.0 + dx, *y)], false)).collect();
for y in &ys {
assert_eq!(s.execute(TRIM, &json!({"at": [50.0 + dx, y], "tolerance": 0.5})).unwrap()["removed"], json!(1));
}
assert_eq!(s.execute(TRIM, &json!({"at": [170.0 + dx, 268.0], "tolerance": 0.5})).unwrap()["removed"], json!(1));
let start = |id: NodeId| path(&s, id).subpaths[0].anchors[0].p;
let ends: Vec<Point> = lines.iter().map(|id| start(*id)).collect();
// Off every path but the lines: the curve's pieces.
let off_curve = |s: &Session, p: Point| {
stack(s).into_iter().filter(|id| !lines.contains(id)).filter_map(|id| path(s, id).nearest(p)).map(|n| n.4).fold(f64::INFINITY, f64::min)
};
let (a, b) = (ends[6], ends[7]);
let click = path(&s, egg).nearest(a.midpoint(b)).unwrap().3;
assert!(off_curve(&s, a) < 1e-3 && off_curve(&s, click) < 1e-3);
assert_eq!(s.execute(TRIM, &json!({"at": [click.x, click.y], "tolerance": 0.5})).unwrap()["removed"], json!(1));
assert!(off_curve(&s, click) > 0.5, "{shift}: the stretch clicked is left");
for (k, e) in ends.iter().enumerate().take(7) {
assert!(off_curve(&s, *e) < 1e-3, "{shift}: the curve no longer reaches line {k}'s end");
}
}
}
+24 -5
View File
@@ -10,8 +10,8 @@ use vectorcraft_doc::{ExportAsset, NodeId};
use super::edit::{refuse_symbol_part, roots_of, selected_roots};
use super::fileio::{
DEFAULT_FORMAT_3D, FORMATS_3D, SCREEN_SETTINGS_KEYS, check_screen_settings, create_dir, export_crop, export_screens, mesh_file_names, mesh_files,
safe_file_name, store_screen_settings, with_screen_export_preset, write_file,
DEFAULT_FORMAT_3D, FORMATS_3D, SCREEN_SETTINGS_KEYS, TEXTURE_SIZE, TEXTURE_SIZES, check_screen_settings, create_dir, export_crop, export_screens,
image_maps, mesh_file_names, mesh_files, safe_file_name, store_screen_settings, textures, with_screen_export_preset, write_file,
};
use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, checked_ids_param, cmd, has_doc, ok, str_param, switch_or, text_param};
@@ -80,7 +80,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Export 3D Assets",
[],
None,
"{assets?: [asset id…] (default every 3D asset), folder?, zip?} each 3D asset's object as a mesh file in its format (assets.set3DFormat), named after the asset: USDA or USDZ, glTF 2.0 (one .gltf, its buffer embedded) or OBJ with its .mtl (whitespace and # in an OBJ's name become _). Every solid of the object (the fill's, each stroke's, a group's members') is a mesh with a material in the color it is painted; faces turned away from the viewer are included, at the object's 3D rotation, y up, about the point it turns about, in points (glTF: meters). Files that would share a name get -2, -3…; an object with a hole that crosses its face's outline or another hole, or with more than 2,000,000 triangles, is refused → {files: [path…]} (no folder: {files: [{name, dataBase64}]}, or with zip one zip as {name, dataBase64, files})",
"{assets?: [asset id…] (default every 3D asset), folder?, zip?, textureSize?: 128…4096 (default 1024: the pixels along the longer side of each face's texture)} each 3D asset's object as a mesh file in its format (assets.set3DFormat), named after the asset: USDA or USDZ, glTF 2.0 (one .gltf, its buffer embedded) or OBJ with its .mtl (whitespace and # in an OBJ's name become _). Every solid of the object (the fill's, each stroke's, a group's members') is a mesh with a material in the color it is painted; faces turned away from the viewer are included, at the object's 3D rotation, y up, about the point it turns about, in points (glTF: meters). The graphics mapped onto a plane or onto Extrude & Bevel's front or back cap (threeD.mapGraphic) are a PNG texture of that face: its color with the graphics drawn over it, flat and unlit, on a mesh of the face's own with texture coordinates; glTF embeds it, USDZ stores it after the layer, and OBJ and USDA write it beside them as <name>-texture-1.png… (whitespace, # and @ become _); a face that is not opaque keeps its opacity in the texture's alpha, and an OBJ also gets <name>-texture-1-opacity.png…, the alpha as gray levels for its map_d. Graphics on Revolve's side are not exported. Files that would share a name get -2, -3…; an object with a hole that crosses its face's outline or another hole, or with more than 2,000,000 triangles, or textures of more than 67,108,864 pixels in one export, is refused → {files: [path…]} (no folder: {files: [{name, dataBase64}]}, or with zip one zip as {name, dataBase64, files})",
has_doc,
export_3d
),
@@ -299,6 +299,8 @@ fn export_3d(s: &mut Session, p: &Value) -> Result<Value> {
}
let folder = text_param(p, "folder", C)?.filter(|f| !f.is_empty());
let zip = switch_or(p, "zip", false, C)?;
let size = texture_size_param(p, C)?;
let mut pixels = 0u64;
// Every file's name, compared without case: a later file that would take one gets -2, -3…
let mut taken: HashSet<String> = HashSet::new();
let mut files: Vec<(String, Vec<u8>)> = vec![];
@@ -311,18 +313,20 @@ fn export_3d(s: &mut Session, p: &Value) -> Result<Value> {
let what = &a.name;
let parts =
vectorcraft_render::effects::three_d_meshes_of_in(Some(d), nodes).map_err(|e| bad(C, format!("{what} can't be exported in 3D: {e}")))?;
let pictures = textures(d, &parts, size, &mut pixels).map_err(|e| bad(C, format!("{what} can't be exported in 3D: {e}")))?;
let images = image_maps(&pictures);
let base = Some(safe_file_name(&a.name)).filter(|b| !b.is_empty()).unwrap_or_else(|| "Asset".into());
let mut stem = base.clone();
let mut k = 1;
loop {
let names = mesh_file_names(&stem, format).map_err(|e| bad(C, e))?;
let names = mesh_file_names(&stem, format, &images).map_err(|e| bad(C, e))?;
if names.iter().all(|n| !taken.contains(&n.to_lowercase())) {
break;
}
k += 1;
stem = format!("{base}-{k}");
}
let made = mesh_files(&stem, format, &parts).map_err(|e| bad(C, e))?;
let made = mesh_files(&stem, format, &parts, &pictures).map_err(|e| bad(C, e))?;
taken.extend(made.iter().map(|(n, _)| n.to_lowercase()));
files.extend(made);
}
@@ -360,6 +364,21 @@ fn export_3d(s: &mut Session, p: &Value) -> Result<Value> {
}
}
/// Param `textureSize` of command `cmd`: the pixels along the longer side of each face's texture,
/// [`TEXTURE_SIZE`] when it is not given.
fn texture_size_param(p: &Value, cmd: &str) -> Result<u32> {
let key = "textureSize";
let (lo, hi) = TEXTURE_SIZES;
match p.get(key) {
None | Some(Value::Null) => Ok(TEXTURE_SIZE),
Some(v) => v
.as_u64()
.and_then(|n| u32::try_from(n).ok())
.filter(|n| (lo..=hi).contains(n))
.ok_or_else(|| bad(cmd, format!("`{key}` must be a whole number of pixels from {lo} to {hi}"))),
}
}
/// The asset ids of param `key`.
fn asset_ids(p: &Value, key: &str, cmd: &str) -> Result<Vec<u64>> {
let ids = p.get(key).and_then(Value::as_array).ok_or_else(|| bad(cmd, format!("`{key}` must be an array of asset ids (see assets.list)")))?;
+2 -1
View File
@@ -38,6 +38,7 @@ mod shape_builder;
mod trace;
pub use live_paint::live_paint_gaps;
pub(crate) use live_paint::{isolated_live_paint, merge_drawn_in_isolation};
use live_paint::{lp_expand, lp_fill, lp_gap_options, lp_info, lp_make, lp_merge, lp_release, lp_stroke_edge};
use shape_builder::{sb_merge, sb_regions};
pub(crate) use trace::TracePresetChanges;
@@ -144,7 +145,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Make",
["Object", "Image Trace"],
None,
"{id?: image or Image Trace group (default: selection), preset?: name (imageTrace.presets), savedPreset?: {settings} (a saved preset's settings, which the journal records so a replay traces with them after the preset is changed, renamed or deleted; used in place of the saved preset `preset` names), enhanced?: false (the preset's enhanced version: with Auto Grouping, and with Shapes in all but High Fidelity Photo; Flat Logo has none and is traced as it is), params?: {mode: \"blackAndWhite\"|\"grayscale\"|\"color\"|\"logo\", threshold: 0-255, palette: \"limited\"|\"fullTone\"|\"automatic\"|\"documentLibrary\" (color mode; limited: the `colors` best colours, fullTone: as many as the tones need, more with colorDetail, automatic: flat art with its own colours, else fullTone, documentLibrary: at most `colors` of the library's colours, as they are), colors: 2-256, colorDetail: 0-100 (fullTone, automatic), library: \"document\" (the document's swatches) or a swatch library id or name (swatch.library.list; documentLibrary), colorGroup?: name (color mode, documentLibrary with library \"document\": the colors of that document color group instead of every swatch; \"\" is every swatch), paths: 0-100, corners: 0-100, noise: px (an area smaller than this joins the color it shares the longest border with; when that color is far from its own and the area is 2 px or more, or a single pixel whose longest border is not tied between colors, it joins the neighboring color nearest its pixels among those sharing at least a tenth of that border), method: \"abutting\"|\"overlapping\" (abutting with fills, not mode logo: a \"Seam Fills\" clip group under the paths holds strokes along the edges two filled paths share, 1.5 image pixels wide (VectorCraft's own width), in the color of the lower path (on an image stretched more one way than another, each stroke's outline in image pixels as a filled path), clipped to the image's box within the traced paths' box; paths that became live shapes get none; the paths are not changed), ignoreWhite (leave out white areas), ignoreColor?: \"#rrggbb\" (with ignoreWhite: the colour left out instead of white), ignoreBackground: false (with ignoreWhite: only the areas of the ignored color that reach the image's edge are left out), keepColors?: [\"#rrggbb\"…] (not mode logo: only the palette colors within about 30 levels of a listed color are traced; empty: every color), snapCurvesToLines, shapes: false (filled outlines that are a circle, an ellipse, a rectangle or a regular polygon come out as that live shape), autoGrouping: false (each path that has others inside it is grouped with them), gradients: false (grayscale and color: an area whose colour changes evenly along one direction is one path with a linear gradient fill), fills: true, strokes: false (Create: lines up to strokeWidth wide become stroked centre lines; without fills, wider areas become stroked outlines), strokeWidth: px (10), logoColors?: [\"#rrggbb\"…] (mode logo: flat-colour logos only; colours found automatically or named here, at most ten; white is its own color, and a named color with every channel 245 or more is taken as that white, except with logoColors named, logoWhite false and no ignoreWhite; noise = areas under noise/10 px ignored; edges to a fraction of a pixel, sharp corners restored, lines and circles snapped; enclosed transparent areas are painted white while white is its own color, and stay holes with ignoreWhite or without a white of its own; fills/strokes are ignored; gradients and photos are refused, judged by the image's own colors also when logoColors are named), logoWhite: true (mode logo with logoColors named; false traces the named colors only: white areas take the nearest of them, a named white is kept and enclosed transparent areas stay holes; with ignoreWhite, white areas are left out either way)}, view?: as imageTrace.setView (default: the traced object's own, else tracingResult), ids?: [id…] (instead of id)} → {id, paths, anchors, colors, warnings: [text…] (the image is over 1500 px on a side, so it traces more slowly; or it was traced scaled down; Flat Logo names only the size it traced a larger image at; or a keepColors color matches none the trace found, or nothing was traced)}",
"{id?: image or Image Trace group (default: selection), preset?: name (imageTrace.presets), savedPreset?: {settings} (a saved preset's settings, which the journal records so a replay traces with them after the preset is changed, renamed or deleted; used in place of the saved preset `preset` names), enhanced?: false (the preset's enhanced version: with Auto Grouping, and with Shapes in all but High Fidelity Photo; Flat Logo has none and is traced as it is), params?: {mode: \"blackAndWhite\"|\"grayscale\"|\"color\"|\"logo\", threshold: 0-255, palette: \"limited\"|\"fullTone\"|\"automatic\"|\"documentLibrary\" (color mode; limited: the `colors` best colours, fullTone: as many as the tones need, more with colorDetail, split into at least colorDetail colors where the image has that many before colors that look alike merge (less than 5 apart in Oklab × 100 and thoroughly mixed, or less than 1.5 and mixed in patches), automatic: flat art with its own colours, else as many as the tones need without fullTone's least count, merging close RGB colors, documentLibrary: at most `colors` of the library's colours, as they are), colors: 2-256, colorDetail: 0-100 (fullTone, automatic), library: \"document\" (the document's swatches) or a swatch library id or name (swatch.library.list; documentLibrary), colorGroup?: name (color mode, documentLibrary with library \"document\": the colors of that document color group instead of every swatch; \"\" is every swatch), paths: 0-100, corners: 0-100, noise: px (an area smaller than this joins the color it shares the longest border with; when that color is far from its own and the area is 2 px or more, or a single pixel whose longest border is not tied between colors, it joins the neighboring color nearest its pixels among those sharing at least a tenth of that border), method: \"abutting\"|\"overlapping\" (abutting with fills, not mode logo: a \"Seam Fills\" clip group under the paths holds strokes along the edges two filled paths share, 1.5 image pixels wide (VectorCraft's own width), in the color of the lower path (on an image stretched more one way than another, each stroke's outline in image pixels as a filled path), clipped to the image's box within the traced paths' box; paths that became live shapes get none; the paths are not changed), ignoreWhite (leave out white areas), ignoreColor?: \"#rrggbb\" (with ignoreWhite: the colour left out instead of white), ignoreBackground: false (with ignoreWhite: only the areas of the ignored color that reach the image's edge are left out), keepColors?: [\"#rrggbb\"…] (not mode logo: only the palette colors within about 30 levels of a listed color are traced; empty: every color), snapCurvesToLines, shapes: false (filled outlines that are a circle, an ellipse, a rectangle or a regular polygon come out as that live shape), autoGrouping: false (each path that has others inside it is grouped with them), gradients: false (grayscale and color: an area whose colour changes evenly along one direction is one path with a linear gradient fill), fills: true, strokes: false (Create: lines up to strokeWidth wide become stroked centre lines; without fills, wider areas become stroked outlines), strokeWidth: px (10), logoColors?: [\"#rrggbb\"…] (mode logo: flat-colour logos only; colours found automatically or named here, at most ten; white is its own color, and a named color with every channel 245 or more is taken as that white, except with logoColors named, logoWhite false and no ignoreWhite; noise = areas under noise/10 px ignored; edges to a fraction of a pixel, sharp corners restored, lines and circles snapped; enclosed transparent areas are painted white while white is its own color, and stay holes with ignoreWhite or without a white of its own; fills/strokes are ignored; gradients and photos are refused, judged by the image's own colors also when logoColors are named), logoWhite: true (mode logo with logoColors named; false traces the named colors only: white areas take the nearest of them, a named white is kept and enclosed transparent areas stay holes; with ignoreWhite, white areas are left out either way)}, view?: as imageTrace.setView (default: the traced object's own, else tracingResult), ids?: [id…] (instead of id)} → {id, paths, anchors, colors, warnings: [text…] (the image is over 1500 px on a side, so it traces more slowly; or it was traced scaled down; Flat Logo names only the size it traced a larger image at; or a keepColors color matches none the trace found, or nothing was traced)}",
has_selection_or_ids,
|s, p| trace_make(s, p, false)
),
+72 -11
View File
@@ -1,8 +1,8 @@
use super::{
Appearance, AppearanceItem, Arc, Beside, Document, EDGE_NAME, EngineError, FACE_NAME, GapOptions, GapSize, LIVE_PAINT_NAME, Node, NodeId,
PathData, Point, Rect, Result, SOURCES_NAME, Selection, Session, SubPath, Value, b, bad, build_children, edge_near, face_at, finite,
fit_to_old_edge, ids_json, is_live_paint, json, number_or, object_param, paint_from, po, point_param, repaint_from, replace_roots, root_ids,
source_nodes, source_shapes, switch_or,
PathData, Point, Rect, Result, Selection, Session, SubPath, Value, b, bad, build_children, edge_near, face_at, finite, fit_to_old_edge, ids_json,
is_live_paint, json, number_or, object_param, paint_from, po, point_param, repaint_from, replace_roots, root_ids, source_nodes, source_shapes,
switch_or,
};
/// `options` as stored on a Live Paint group: none for the defaults.
@@ -53,6 +53,27 @@ fn make_live(d: &mut Document, sel: &mut Selection, roots: &[NodeId]) -> Result<
Ok((gid, nf, ne))
}
/// The children of Live Paint group `g` besides its sources group ([`b::sources`]) and its faces and
/// edges (paths named [`FACE_NAME`] or [`EDGE_NAME`]), back to front: objects drawn in it in
/// isolation mode. A group or other object named like a part is one of them.
fn others_in(g: &Node) -> impl Iterator<Item = &Arc<Node>> {
let src = b::sources(g).map(|s| s.id);
g.children()
.into_iter()
.flatten()
.filter(move |c| Some(c.id) != src && !(c.path_data().is_some() && matches!(c.name.as_deref(), Some(FACE_NAME | EDGE_NAME))))
}
/// Make `parts` (a sources group, faces and edges made again) the children of Live Paint group `g`,
/// with its other children ([`others_in`]) that are not among `gone` kept in front of them, in their
/// order.
fn set_parts(g: &mut Node, mut parts: Vec<Arc<Node>>, gone: &[NodeId]) {
parts.extend(others_in(g).filter(|c| !gone.contains(&c.id)).cloned());
if let Some(ch) = g.children_mut() {
*ch = parts;
}
}
/// Select `ids` alone, without an undo step, when they are not selected that way already.
fn select_only(s: &mut Session, ids: &[NodeId]) -> Result<()> {
let st = s.doc()?;
@@ -134,9 +155,15 @@ fn merge_live(d: &mut Document, sel: &mut Selection, roots: &[NodeId]) -> Result
b::faces(&old).iter().filter(|f| draws(f)).filter_map(|f| Some((po::interior_point(f.path_data()?)?, Carried::of(f)))).collect();
let old_parts = old.clone();
let mut sources = source_nodes(&old);
// The objects drawn in the other Live Paint groups besides their parts stay in the merged group.
let mut others = vec![];
for r in roots {
if *r != target {
sources.extend(source_nodes(d.node(*r).ok_or(EngineError::NoNode(*r))?));
let n = d.node(*r).ok_or(EngineError::NoNode(*r))?;
sources.extend(source_nodes(n));
if is_live_paint(n) {
others.extend(others_in(n).cloned());
}
}
}
// Merge applies the Gap Options' merge rules to the groups' options, bottom-most first.
@@ -146,8 +173,9 @@ fn merge_live(d: &mut Document, sel: &mut Selection, roots: &[NodeId]) -> Result
// The group keeps its name, lock, visibility, transparency, appearance, opacity mask, graphic
// style link and the rest; its children are made again and its Gap Options set to the merged ones.
let mut g = old;
set_parts(&mut g, children, roots);
if let Some(ch) = g.children_mut() {
*ch = children;
ch.extend(others);
}
g.extras_mut().live_paint_gaps = stored_gap_options(options);
for (pt, carried) in keep_faces {
@@ -199,6 +227,38 @@ pub(super) fn lp_merge(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "id": id.0, "faces": faces, "edges": edges }))
}
/// The Live Paint group whose drawn art is added when isolation mode leaves `isolated`: the innermost
/// Live Paint group that is `isolated` or holds it, such as a group drawn in an isolated Live Paint
/// group and then isolated itself. None when `isolated` is not in a Live Paint group.
pub(crate) fn isolated_live_paint(d: &Document, isolated: NodeId) -> Option<NodeId> {
d.ancestry(isolated)?.into_iter().rev().find(|id| d.node(*id).is_some_and(is_live_paint))
}
/// The children of Live Paint group `g` besides its parts ([`others_in`]) that Live Paint takes
/// ([`b::live_paint_takes`]) and that are shown and unlocked with everything in them, back to
/// front: the paths drawn in it in isolation mode.
fn drawn_in(g: &Node) -> Vec<NodeId> {
fn open(n: &Node) -> bool {
n.visible && !n.locked && n.children().is_none_or(|ch| ch.iter().all(|c| open(c)))
}
others_in(g).filter(|c| open(c) && b::live_paint_takes(c)).map(|c| c.id).collect()
}
/// Leaving isolation mode in Live Paint group `g` adds the paths drawn in it to the group as
/// `livePaint.merge` does, in one "Merge Live Paint" undo step; → whether any were added. Type,
/// images, other objects Live Paint does not take, and hidden or locked objects stay where they
/// are. With nothing to add, or when `g` is not a Live Paint group, nothing changes and no undo
/// step is recorded.
pub(crate) fn merge_drawn_in_isolation(s: &mut Session, g: NodeId) -> Result<bool> {
let drawn = s.doc()?.doc.node(g).filter(|n| is_live_paint(n)).map(drawn_in).unwrap_or_default();
if drawn.is_empty() {
return Ok(false);
}
let roots: Vec<NodeId> = std::iter::once(g).chain(drawn).collect();
s.edit("Merge Live Paint", |d, sel| merge_live(d, sel, &roots))?;
Ok(true)
}
fn live_targets(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
let d = &s.doc()?.doc;
let ids = root_ids(s, p)?;
@@ -216,7 +276,8 @@ pub(super) fn lp_release(s: &mut Session, p: &Value) -> Result<Value> {
let mut released = Beside::replacing(d, &targets);
for g in &targets {
let n = d.node(*g).cloned().ok_or(EngineError::NoNode(*g))?;
let srcs: Vec<Node> = source_nodes(&n).iter().map(|c| (**c).clone()).collect();
// The objects drawn in the group besides its parts are released in front of its paths.
let srcs: Vec<Node> = source_nodes(&n).iter().chain(others_in(&n)).map(|c| (**c).clone()).collect();
out.extend(srcs.iter().map(|c| c.id));
released.put(d, *g, srcs)?;
}
@@ -245,10 +306,12 @@ pub(super) fn lp_expand(s: &mut Session, p: &Value) -> Result<Value> {
e.trace = None;
e.live_paint_gaps = None;
}
// Objects drawn in the group ([`others_in`]) stay, whatever they are named.
let src = b::sources(n).map(|c| c.id);
if let Some(ch) = n.children_mut() {
ch.retain(|c| match c.name.as_deref() {
Some(SOURCES_NAME) => false,
Some(FACE_NAME | EDGE_NAME) => draws(c),
_ if Some(c.id) == src => false,
Some(FACE_NAME | EDGE_NAME) if c.path_data().is_some() => draws(c),
_ => true,
});
}
@@ -354,9 +417,7 @@ pub(super) fn lp_gap_options(s: &mut Session, p: &Value) -> Result<Value> {
// The faces change only with what paint stops at, or with new paths.
if added > 0 || options.max_gap() != old.gap_options().max_gap() {
let (children, _, _) = build_children(d, sources, options.max_gap())?;
if let Some(ch) = n.children_mut() {
*ch = children;
}
set_parts(&mut n, children, &[]);
repaint_from(&mut n, &old);
}
n.extras_mut().live_paint_gaps = stored_gap_options(options);
+1 -1
View File
@@ -209,7 +209,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Load Metafile into Clipboard",
[],
None,
"{dataBase64 (EMF or WMF bytes), center?: [x, y]} replace the clipboard with the picture's objects (paths, clipping groups, images, point type; the images they use), centred on `center` (default: the first artboard) → {count, warnings}; records VectorCraft doesn't read are skipped with one warning; then run edit.paste",
"{dataBase64 (EMF or WMF bytes), center?: [x, y]} replace the clipboard with the picture's objects (paths, clipping groups, images, point type; the images they use), centred on `center` (default: the first artboard) → {count, warnings}; records VectorCraft doesn't read are skipped with one warning; a picture cut short by a reader limit, images and pattern brushes that can't be read, clips that can't be applied and raster operations other than a plain copy each add a warning; then run edit.paste",
has_doc,
import_emf
),
+26 -12
View File
@@ -67,7 +67,15 @@ pub fn specs() -> Vec<CommandSpec> {
circle_through_points
),
cmd!("shape.line", "Line Segment", [], None, "{x1, y1, x2, y2, fill?: bool (Fill Line: the current fill, else none)} → {id}", has_doc, line),
cmd!("shape.spiral", "Spiral", [], None, "{cx, cy, radius, decay=80 (%), segments=10, clockwise?} → {id}", has_doc, spiral),
cmd!(
"shape.spiral",
"Spiral",
[],
None,
"{cx, cy, radius, decay=80 (%), segments=10, clockwise?, rotation?: deg clockwise about (cx, cy)} (0: outer end at (cx + radius, cy)) → {id}",
has_doc,
spiral
),
cmd!(
"shape.arc",
"Arc",
@@ -125,13 +133,6 @@ pub fn specs() -> Vec<CommandSpec> {
]
}
/// Insert a new object at the top of the insertion parent with the current paint and new-art
/// template; select it.
pub(crate) fn add_art(s: &mut Session, label: &str, kind: NodeKind, name: Option<String>) -> Result<Value> {
let look = s.new_art_look(s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width);
add_look(s, label, kind, look, name)
}
/// Insert a new object looking like `look` (drawing modes apply); select it.
pub(crate) fn add_look(s: &mut Session, label: &str, kind: NodeKind, look: NewArt, name: Option<String>) -> Result<Value> {
insert_look(s, label, kind, look, name, true)
@@ -143,7 +144,8 @@ pub(crate) fn insert_look(s: &mut Session, label: &str, kind: NodeKind, look: Ne
insert_look_turned(s, label, kind, look, name, select, 0.0, true)
}
/// [`add_art`] for an object made turned by a `rotation` param (degrees, clockwise on the page):
/// Insert a new object at the top of the insertion parent with the current paint and new-art
/// template, made turned by a `rotation` param (degrees, clockwise on the page), and select it:
/// its bounding box turns with it, as after the Rotate tool.
fn add_art_turned(s: &mut Session, label: &str, kind: NodeKind, rotation: f64) -> Result<Value> {
let look = s.new_art_look(s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width);
@@ -321,7 +323,7 @@ fn path_kind(path: PathData, live: Option<LiveShape>) -> NodeKind {
/// a box (rectangle, ellipse, grid) runs along the turned axes from `pivot`, the point the dialog
/// placed at the click (its top-left corner `x`, `y`, or a grid's reference point), which stays
/// put; an arc sized by its lengths turns about its reference point `x`, `y`, which the dialog
/// placed at the click; a polygon or star turns its base orientation about its centre. The params as they are at
/// placed at the click; a polygon, star or spiral turns its base orientation about its centre. The params as they are at
/// 0° or a whole turn, for other commands and when they already carry a `rotation`.
pub fn constrain_click(s: &Session, cmd: &str, mut params: Value, pivot: Point) -> Value {
let base = s.prefs.constrain_angle;
@@ -337,7 +339,7 @@ pub fn constrain_click(s: &Session, cmd: &str, mut params: Value, pivot: Point)
o.insert("y".into(), json!(c.y - h / 2.0));
o.insert("rotation".into(), json!(rotation));
}
"shape.polygon" | "shape.star" => {
"shape.polygon" | "shape.star" | "shape.spiral" => {
o.insert("rotation".into(), json!(rotation));
}
"shape.arc" if o.contains_key("lengthX") || o.contains_key("lengthY") => {
@@ -673,6 +675,10 @@ fn line(s: &mut Session, p: &Value) -> Result<Value> {
}
fn spiral(s: &mut Session, p: &Value) -> Result<Value> {
let rotation = if p.get("rotation").is_some() { f64_req(p, "rotation", "shape.spiral")? } else { 0.0 };
if !rotation.is_finite() {
return Err(bad("shape.spiral", "rotation must be finite"));
}
let c = Point::new(f64_req(p, "cx", "shape.spiral")?, f64_req(p, "cy", "shape.spiral")?);
let segments = count_or(p, "segments", 10, "shape.spiral")?.clamp(2, 1000) as u32;
let path = shapes::spiral(
@@ -682,7 +688,15 @@ fn spiral(s: &mut Session, p: &Value) -> Result<Value> {
segments,
switch_or(p, "clockwise", true, "shape.spiral")?,
);
add_art(s, "Spiral", path_kind(path, None), None)
// The outer end turns clockwise from (cx + radius, cy) about the center; 0 and whole turns
// leave the path as it is, and quarter turns are exact.
let path = if bbox_turn(rotation) == 0.0 {
path
} else {
let c = c.to_vec2();
path.transformed(Affine::translate(c) * vectorcraft_geom::rotate_deg(rotation) * Affine::translate(-c))
};
add_art_turned(s, "Spiral", path_kind(path, None), constrained_turn(s, rotation))
}
fn arc(s: &mut Session, p: &Value) -> Result<Value> {
+5 -3
View File
@@ -39,7 +39,7 @@ pub mod jxlread;
mod legacy_ai;
mod load;
mod mesh3d;
pub(crate) use load::{MAX_RASTER_ALLOC, file_clipped, png_clip, size_note};
pub(crate) use load::{MAX_RASTER_ALLOC, file_clipped, image_clip, size_note};
mod heifread;
mod hpgl;
mod jp2read;
@@ -87,8 +87,10 @@ pub use load::{
};
pub(crate) use load::{check_files_not_lossy_overwrite, check_not_lossy_overwrite, lossy_source};
pub use load::{losses_summary, overwrite_losses};
pub use mesh3d::{DEFAULT_FORMAT_3D, FORMATS_3D, format_3d_label};
pub(crate) use mesh3d::{mesh_file_names, mesh_files};
#[cfg(test)]
pub(crate) use mesh3d::MAX_TEXTURE_PIXELS;
pub use mesh3d::{DEFAULT_FORMAT_3D, FORMATS_3D, draws_textures, format_3d_label};
pub(crate) use mesh3d::{TEXTURE_SIZE, TEXTURE_SIZES, image_maps, mesh_file_names, mesh_files, textures};
pub use naming::{NameParts as FileNameParts, parse_date as parse_file_date, render as render_file_name};
pub(crate) use native::preview_png;
pub use native::with_compression_pref;
File diff suppressed because one or more lines are too long
+6 -11
View File
@@ -211,17 +211,11 @@ fn selected_part(n: &Arc<Node>, keep: &HashSet<NodeId>, holders: &HashSet<NodeId
/// its own art, not a whole document of artboards. `renderer` measures the 3D art, and keeps it for
/// the next artboard of the same document.
pub(super) fn art_over(doc: &Document, rect: vectorcraft_geom::Rect, renderer: &mut vectorcraft_render::Renderer) -> Document {
fn kept(
n: &Arc<Node>,
doc: &Document,
symbols: &SymbolBoxes,
rect: vectorcraft_geom::Rect,
renderer: &mut vectorcraft_render::Renderer,
) -> Option<Arc<Node>> {
fn kept(n: &Arc<Node>, symbols: &SymbolBoxes, rect: vectorcraft_geom::Rect, renderer: &mut vectorcraft_render::Renderer) -> Option<Arc<Node>> {
if matches!(n.kind, NodeKind::Layer { clip: false, .. }) {
let mut layer = Node::clone(n);
let children = layer.children_mut()?;
*children = children.iter().filter_map(|c| kept(c, doc, symbols, rect, renderer)).collect();
*children = children.iter().filter_map(|c| kept(c, symbols, rect, renderer)).collect();
return Some(Arc::new(layer));
}
// A group that doesn't clip keeps only its members over the artboard, so art gathered in one
@@ -230,20 +224,21 @@ pub(super) fn art_over(doc: &Document, rect: vectorcraft_geom::Rect, renderer: &
if matches!(n.kind, NodeKind::Group { clip: false, .. }) && n.appearance.effects.is_empty() {
let mut group = Node::clone(n);
let children = group.children_mut()?;
*children = children.iter().filter_map(|c| kept(c, doc, symbols, rect, renderer)).collect();
*children = children.iter().filter_map(|c| kept(c, symbols, rect, renderer)).collect();
return (!children.is_empty()).then(|| Arc::new(group));
}
let over = |b: vectorcraft_geom::Rect| b.x0 <= rect.x1 && rect.x0 <= b.x1 && b.y0 <= rect.y1 && rect.y0 <= b.y1;
let mut holds_instance = false;
n.walk(&mut |c| holds_instance |= matches!(c.kind, NodeKind::SymbolInstance { .. }));
let painted = || holds_instance && vectorcraft_render::painted_bounds(doc, n).is_some_and(over);
// Measured in boxes of its own, which find symbols through the same index.
let painted = || holds_instance && vectorcraft_render::painted_bounds_with(&symbols.unmeasured(), n).is_some_and(over);
let reach = vectorcraft_brush::reach_within(n);
let brushed = |b: vectorcraft_geom::Rect| over(if reach > 0.0 { b.inflate(reach, reach) } else { b });
(n.visual_bounds_with(symbols).is_none_or(brushed) || renderer.effect_bounds(symbols, n).is_some_and(brushed) || painted()).then(|| n.clone())
}
let symbols = doc.symbol_boxes().with_brush_art();
let mut d = doc.clone();
d.layers = doc.layers.iter().filter_map(|l| kept(l, doc, &symbols, rect, renderer)).collect();
d.layers = doc.layers.iter().filter_map(|l| kept(l, &symbols, rect, renderer)).collect();
d
}
+44 -6
View File
@@ -60,8 +60,7 @@ impl Loaded {
}
}
/// An image ready to embed: PNG/JPEG/GIF/WebP keep their bytes, other formats are stored as PNG
/// (what browsers, PDF and SVG viewers show).
/// An image ready to embed. CMYK images use JPEG or TIFF; other images use browser-readable formats.
#[derive(Clone)]
pub struct RasterImage {
/// Content key for `Document::images` (identical files share one blob).
@@ -937,8 +936,9 @@ pub(crate) fn size_note(bytes: &[u8]) -> Option<String> {
/// ink are written again with their inks together ([`vectorcraft_doc::cmyk::stored_cmyk_tiff`]);
/// CMYK TIFFs with an alpha channel, which the decoder can't read, become RGBA in the active color
/// settings' CMYK, whichever of their extra channels is the alpha
/// ([`vectorcraft_doc::cmyk::extra_samples_tiff_rgba`]), as do CMYK Photoshop documents, whose
/// merged image is read ([`psdread`]).
/// ([`vectorcraft_doc::cmyk::extra_samples_tiff_rgba`]). Opaque CMYK PSD/PSB merged images retain
/// 8- or 16-bit inks and their CMYK ICC profile as TIFF, within the native CMYK pixel and allocation limits;
/// other CMYK composites use the RGBA decoder's allocation limit ([`psdread`]).
/// 1-bit TIFFs compressed with CCITT Group 3, which the decoder can't read either, become RGBA
/// too ([`vectorcraft_doc::cmyk::group3_tiff_rgba`]).
/// Grayscale TIFFs with an alpha channel or other extra channels, which the decoder can't read
@@ -961,14 +961,27 @@ pub(crate) fn size_note(bytes: &[u8]) -> Option<String> {
/// or TIFF keeps its inks, at the 8 or 16 bits the file has, and its CMYK ICC profile as a CMYK
/// TIFF ([`vectorcraft_doc::cmyk::turned_cmyk`]). An image the decoder reads and that is stored as
/// PNG keeps its gray or RGB samples at 8 or 16 bits, and the gray or RGB ICC profile they are in;
/// other samples become 8-bit RGBA. A Photoshop document's PNG keeps the clipping path the file
/// names ([`png_with_clip`]).
/// other samples become 8-bit RGBA. A PSD/PSB composite's stored image keeps its imported
/// clipping path ([`image_clip`]).
pub fn raster_image(bytes: &[u8]) -> Result<RasterImage> {
let ppi = super::ppi::resolution(bytes);
if let Some((w, h)) = vectorcraft_doc::cmyk::oversized_tiff(bytes) {
return Err(err(format!("an image of {w} × {h} pixels is too large to draw")));
}
if psdread::is_psd(bytes) {
if let Some(mut native) = psdread::decode_cmyk(bytes, MAX_RASTER_ALLOC).map_err(err)? {
native.meta.dpi = ppi.map(|(x, y)| (x as f32, y as f32));
let clip = psdread::clipping_path(bytes).and_then(|path| {
let json = serde_json::to_string(&path).ok().filter(|j| j.len() <= MAX_PNG_CLIP)?;
native.meta.text.push(("Description".into(), format!("{CLIP_KEYWORD}\n{json}")));
Some((path, vectorcraft_geom::FillRule::EvenOdd))
});
let data =
craft_image_codecs::encode(&native, craft_image_codecs::Format::Tiff, &craft_image_codecs::EncodeOptions::default()).map_err(err)?;
let mut img = stored(data, "image/tiff", native.dimensions(), ppi)?;
img.clip = clip;
return Ok(img);
}
let cms = vectorcraft_color::cms::active();
let img = as_png(psdread::decode(bytes, MAX_RASTER_ALLOC, |c| cms.cmyk_to_srgb(c, false)).map_err(err)?, None, ppi)?;
return Ok(png_with_clip(img, psdread::clipping_path(bytes)));
@@ -1173,6 +1186,31 @@ pub(crate) fn png_clip(png: &[u8]) -> Option<vectorcraft_geom::PathData> {
vectorcraft_geom::path::with_anchor_budget(vectorcraft_geom::path::MAX_READ_ANCHORS, || serde_json::from_slice(json).ok())
}
/// The imported clipping-path marker in a stored PNG or CMYK TIFF, within the path budget.
pub(crate) fn image_clip(blob: &ImageBlob) -> Option<vectorcraft_geom::PathData> {
if blob.mime == "image/png" {
return png_clip(&blob.bytes);
}
if blob.mime != "image/tiff" {
return None;
}
use tiff::tags::{Tag, Type, ValueBuffer};
let mut d = tiff::decoder::Decoder::new(std::io::Cursor::new(blob.bytes.as_slice())).ok()?;
let mut ifd = d.image_ifd();
let entry = ifd.find_entry(Tag::ImageDescription)?;
if entry.field_type() != Type::ASCII || entry.count() > (MAX_PNG_CLIP + CLIP_KEYWORD.len() + 2) as u64 {
return None;
}
let mut buf = ValueBuffer::empty(Type::ASCII);
ifd.find_tag_buf(Tag::ImageDescription, &mut buf).ok()??;
let json = buf.as_bytes().strip_prefix(CLIP_KEYWORD.as_bytes())?.strip_prefix(b"\n")?;
let json = json.strip_suffix(b"\0").unwrap_or(json);
if json.len() > MAX_PNG_CLIP {
return None;
}
vectorcraft_geom::path::with_anchor_budget(vectorcraft_geom::path::MAX_READ_ANCHORS, || serde_json::from_slice(json).ok())
}
/// An image as a document of its physical size at the resolution it declares (as Place sizes it;
/// 72 ppi, 1 px = 1 pt, when it declares none), the image named after the file.
pub(super) fn raster_doc(name: &str, bytes: &[u8]) -> Result<Document> {
+378 -47
View File
@@ -9,13 +9,24 @@
//! as their specifications ask; MTL colors are the display colors. Materials are two-sided, since
//! an open solid or a turned plane is seen from both sides.
//!
//! The graphics mapped onto a face of a solid ([`textures`]) are a PNG picture of that face: its
//! color with the graphics drawn over it, flat and unshaded, which the face's own mesh shows through
//! texture coordinates and a material of its own. glTF embeds each PNG as a data URI, USDZ stores it
//! after the layer, and OBJ and USDA name PNG files written beside them (`<name>-texture-1.png`…).
//!
//! Formats: glTF 2.0 <https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html>, USD
//! <https://openusd.org/release/index.html> (USDZ: <https://openusd.org/release/spec_usdz.html>).
//! <https://openusd.org/release/index.html> (USDZ: <https://openusd.org/release/spec_usdz.html>;
//! textures: <https://openusd.org/release/spec_usdpreviewsurface.html>), OBJ and MTL
//! <https://www.loc.gov/preservation/digital/formats/fdd/fdd000508.shtml>.
use std::fmt::Write as _;
use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_render::effects::SolidMesh;
use vectorcraft_doc::color::{Color, Paint};
use vectorcraft_doc::{Appearance, Document, Node, NodeId};
use vectorcraft_geom::{Affine, Rect};
use vectorcraft_render::effects::{MeshGraphics, SolidMesh};
/// The formats a 3D asset exports to, as `assets.set3DFormat` names them: USDA first, the default.
pub const FORMATS_3D: [&str; 4] = ["usda", "usdz", "gltf", "obj"];
@@ -23,6 +34,12 @@ pub const FORMATS_3D: [&str; 4] = ["usda", "usdz", "gltf", "obj"];
pub const DEFAULT_FORMAT_3D: &str = "usda";
/// The meters in a point (1/72 inch).
const METERS_PER_POINT: f64 = 0.0254 / 72.0;
/// The pixels along the longer side of a face's texture, unless `assets.export3D` is given another
/// size, and the sizes it takes.
pub(crate) const TEXTURE_SIZE: u32 = 1024;
pub(crate) const TEXTURE_SIZES: (u32, u32) = (128, 4096);
/// The most texture pixels one export draws, all its assets together.
pub(crate) const MAX_TEXTURE_PIXELS: u64 = 4 * 4096 * 4096;
/// The label of `format` for menus: `USDA`, `USDZ`, `glTF`, `OBJ`.
pub fn format_3d_label(format: &str) -> &'static str {
@@ -40,14 +57,44 @@ fn obj_stem(stem: &str) -> String {
stem.chars().map(|c| if c.is_whitespace() || c == '#' { '_' } else { c }).collect()
}
/// The names of the files [`mesh_files`] writes for `stem` in `format`.
pub(crate) fn mesh_file_names(stem: &str, format: &str) -> Result<Vec<String>, String> {
/// The name of texture `k` (from 0) of the object named `stem`: whitespace, `#` and `@` become `_`,
/// so an MTL `map_Kd` line and a USD asset path name it as one word.
fn texture_name(stem: &str, k: usize) -> String {
format!("{}-texture-{}.png", texture_stem(stem), k + 1)
}
/// The name of the opacity map of texture `k` (from 0) of the object named `stem`, as
/// [`texture_name`] names the texture.
fn opacity_name(stem: &str, k: usize) -> String {
format!("{}-texture-{}-opacity.png", texture_stem(stem), k + 1)
}
/// `stem` with whitespace, `#` and `@` turned into `_`, for the names of its textures.
fn texture_stem(stem: &str) -> String {
stem.chars().map(|c| if c.is_whitespace() || c == '#' || c == '@' { '_' } else { c }).collect()
}
/// The names of the files [`mesh_files`] writes for `stem` in `format` with the textures `images`
/// ([`image_maps`]: for each, whether it has an opacity map): OBJ and USDA name a PNG file for each
/// texture after them, and OBJ also one for each opacity map, after its texture; glTF and USDZ hold
/// theirs.
pub(crate) fn mesh_file_names(stem: &str, format: &str, images: &[bool]) -> Result<Vec<String>, String> {
let beside = |mut names: Vec<String>, stem: &str, maps: bool| {
for (k, map) in images.iter().enumerate() {
names.push(texture_name(stem, k));
if maps && *map {
names.push(opacity_name(stem, k));
}
}
names
};
match format {
"obj" => {
let stem = obj_stem(stem);
Ok(vec![format!("{stem}.obj"), format!("{stem}.mtl")])
Ok(beside(vec![format!("{stem}.obj"), format!("{stem}.mtl")], &stem, true))
}
"gltf" | "usda" | "usdz" => Ok(vec![format!("{stem}.{format}")]),
"usda" => Ok(beside(vec![format!("{stem}.usda")], stem, false)),
"gltf" | "usdz" => Ok(vec![format!("{stem}.{format}")]),
_ => {
let key = "format";
Err(format!("`{key}` must be one of {}", FORMATS_3D.join(", ")))
@@ -55,35 +102,109 @@ pub(crate) fn mesh_file_names(stem: &str, format: &str) -> Result<Vec<String>, S
}
}
/// A picture painted on one part of a 3D object ([`SolidMesh`]): a PNG, and for each corner of the
/// part's mesh where it falls on the picture (0 to 1 across from the left, 0 to 1 down from the
/// top). `opacity` is a grayscale PNG of the picture's alpha when some of it is not opaque.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct Texture {
pub png: Arc<Vec<u8>>,
pub opacity: Option<Arc<Vec<u8>>>,
pub uv: Vec<[f64; 2]>,
}
/// A distinct picture of a 3D object: the PNG and its opacity map.
type Picture = (Arc<Vec<u8>>, Option<Arc<Vec<u8>>>);
/// The distinct pictures of `textures` in order of first use, and the index among them of each
/// part's (`None` for a part without one).
fn images(parts: usize, textures: &[Option<Texture>]) -> (Vec<Picture>, Vec<Option<usize>>) {
let mut out: Vec<Picture> = vec![];
let index = (0..parts)
.map(|k| {
let t = textures.get(k)?.as_ref()?;
Some(out.iter().position(|(p, _)| Arc::ptr_eq(p, &t.png) || p == &t.png).unwrap_or_else(|| {
out.push((t.png.clone(), t.opacity.clone()));
out.len() - 1
}))
})
.collect();
(out, index)
}
/// For each distinct picture of `textures`, whether it has an opacity map ([`mesh_file_names`]).
pub(crate) fn image_maps(textures: &[Option<Texture>]) -> Vec<bool> {
images(textures.len(), textures).0.iter().map(|(_, map)| map.is_some()).collect()
}
/// The files of a 3D object named `stem` in `format` ([`FORMATS_3D`]): `(file name, bytes)`, the
/// OBJ with its MTL after it.
pub(crate) fn mesh_files(stem: &str, format: &str, parts: &[SolidMesh]) -> Result<Vec<(String, Vec<u8>)>, String> {
let names = mesh_file_names(stem, format)?;
let bytes = match format {
/// OBJ with its MTL after it and the PNG files of `textures` last (an OBJ's opacity maps each after
/// its texture). `textures` holds the picture of each part that has one, in the order of `parts`.
pub(crate) fn mesh_files(stem: &str, format: &str, parts: &[SolidMesh], textures: &[Option<Texture>]) -> Result<Vec<(String, Vec<u8>)>, String> {
let (images, image) = images(parts.len(), textures);
let maps: Vec<bool> = images.iter().map(|(_, map)| map.is_some()).collect();
let names = mesh_file_names(stem, format, &maps)?;
let pictures: Vec<Arc<Vec<u8>>> = images.iter().map(|(p, _)| p.clone()).collect();
let scene = Scene { parts, textures, image: &image, pictures: &pictures, maps: &maps };
let pngs = || pictures.iter().map(|p| p.as_ref().clone());
let bytes: Vec<Vec<u8>> = match format {
"obj" => {
let (obj, mtl) = obj(&obj_stem(stem), parts);
vec![obj.into_bytes(), mtl.into_bytes()]
let stem = obj_stem(stem);
let (obj, mtl) = obj(&stem, &scene);
let with_maps = images.iter().flat_map(|(p, map)| std::iter::once(p.as_ref().clone()).chain(map.as_ref().map(|m| m.as_ref().clone())));
[obj.into_bytes(), mtl.into_bytes()].into_iter().chain(with_maps).collect()
}
"gltf" => vec![gltf(stem, &scene).into_bytes()],
"usda" => std::iter::once(usda(stem, &scene).into_bytes()).chain(pngs()).collect(),
_ => {
let mut members = vec![(format!("{stem}.usda"), usda(stem, &scene).into_bytes())];
members.extend(pngs().enumerate().map(|(k, png)| (texture_name(stem, k), png)));
vec![super::zip::store_aligned(&members, 64)?]
}
"gltf" => vec![gltf(stem, parts).into_bytes()],
"usda" => vec![usda(stem, parts).into_bytes()],
_ => vec![super::zip::store_aligned(&[(format!("{stem}.usda"), usda(stem, parts).into_bytes())], 64)?],
};
Ok(names.into_iter().zip(bytes).collect())
}
/// The distinct colors of `parts` in order, and each part's index among them.
fn materials(parts: &[SolidMesh]) -> (Vec<[f32; 4]>, Vec<usize>) {
let mut colors: Vec<[f32; 4]> = vec![];
let index = parts
/// The parts of an object with their pictures: `image` is each part's index among `pictures`, and
/// `maps` says for each picture whether it has an opacity map.
struct Scene<'a> {
parts: &'a [SolidMesh],
textures: &'a [Option<Texture>],
image: &'a [Option<usize>],
pictures: &'a [Arc<Vec<u8>>],
maps: &'a [bool],
}
impl Scene<'_> {
/// Part `k`'s texture coordinates and picture, when it has a picture.
fn texture(&self, k: usize) -> Option<(&[[f64; 2]], usize)> {
let t = self.textures.get(k)?.as_ref()?;
Some((t.uv.as_slice(), (*self.image.get(k)?)?))
}
}
/// A material: a color, with a picture that replaces its red, green and blue.
#[derive(Clone, Copy, PartialEq)]
struct Material {
color: [f32; 4],
image: Option<usize>,
}
/// The distinct materials of `scene`'s parts in order, and each part's index among them.
fn materials(scene: &Scene) -> (Vec<Material>, Vec<usize>) {
let mut out: Vec<Material> = vec![];
let index = scene
.parts
.iter()
.map(|p| {
colors.iter().position(|c| *c == p.color).unwrap_or_else(|| {
colors.push(p.color);
colors.len() - 1
.enumerate()
.map(|(k, p)| {
let m = Material { color: p.color, image: scene.texture(k).map(|(_, i)| i) };
out.iter().position(|c| *c == m).unwrap_or_else(|| {
out.push(m);
out.len() - 1
})
})
.collect();
(colors, index)
(out, index)
}
/// An sRGB channel (0..1) as linear light.
@@ -96,8 +217,9 @@ fn num(v: f64) -> String {
format!("{v}")
}
fn obj(stem: &str, parts: &[SolidMesh]) -> (String, String) {
let (colors, material) = materials(parts);
fn obj(stem: &str, scene: &Scene) -> (String, String) {
let parts = scene.parts;
let (materials, material) = materials(scene);
let mut o = String::new();
let _ = writeln!(o, "mtllib {stem}.mtl");
let _ = writeln!(o, "o {stem}");
@@ -106,33 +228,64 @@ fn obj(stem: &str, parts: &[SolidMesh]) -> (String, String) {
let _ = writeln!(o, "v {} {} {}", num(v[0]), num(v[1]), num(v[2]));
}
}
// OBJ's texture coordinates run up from the picture's bottom.
for k in 0..parts.len() {
for uv in scene.texture(k).map(|(uv, _)| uv).unwrap_or_default() {
let _ = writeln!(o, "vt {} {}", num(uv[0]), num(1.0 - uv[1]));
}
}
for p in parts {
for n in &p.mesh.normals {
let _ = writeln!(o, "vn {} {} {}", num(n[0]), num(n[1]), num(n[2]));
}
}
let mut base = 1usize;
let (mut base, mut uv_base) = (1usize, 1usize);
for (k, p) in parts.iter().enumerate() {
let _ = writeln!(o, "g Solid_{}", k + 1);
let _ = writeln!(o, "usemtl Material_{}", material.get(k).copied().unwrap_or(0) + 1);
let textured = scene.texture(k).filter(|(uv, _)| uv.len() == p.mesh.positions.len()).is_some();
for t in &p.mesh.triangles {
let [a, b, c] = t.map(|i| i as usize + base);
let _ = writeln!(o, "f {a}//{a} {b}//{b} {c}//{c}");
if textured {
let [a, b, c] = t.map(|i| i as usize);
let corner = |i: usize| format!("{}/{}/{}", i + base, i + uv_base, i + base);
let _ = writeln!(o, "f {} {} {}", corner(a), corner(b), corner(c));
} else {
let [a, b, c] = t.map(|i| i as usize + base);
let _ = writeln!(o, "f {a}//{a} {b}//{b} {c}//{c}");
}
}
base += p.mesh.positions.len();
uv_base += scene.texture(k).map_or(0, |(uv, _)| uv.len());
}
let mut m = String::new();
for (k, c) in colors.iter().enumerate() {
for (k, mat) in materials.iter().enumerate() {
let c = mat.color;
let _ = writeln!(m, "newmtl Material_{}", k + 1);
let _ = writeln!(m, "Kd {} {} {}", num(f64::from(c[0])), num(f64::from(c[1])), num(f64::from(c[2])));
let _ = writeln!(m, "d {}", num(f64::from(c[3])));
match mat.image {
// The picture holds the color; Kd multiplies it.
Some(_) => {
let _ = writeln!(m, "Kd 1 1 1");
}
None => {
let _ = writeln!(m, "Kd {} {} {}", num(f64::from(c[0])), num(f64::from(c[1])), num(f64::from(c[2])));
}
}
// A picture's opacity map holds the opacity, as gray levels.
let _ = writeln!(m, "d {}", if mat.image.is_some() { "1".to_string() } else { num(f64::from(c[3])) });
let _ = writeln!(m, "illum 1");
if let Some(i) = mat.image {
let _ = writeln!(m, "map_Kd -clamp on {}", texture_name(stem, i));
if scene.maps.get(i).copied().unwrap_or(false) {
let _ = writeln!(m, "map_d -clamp on {}", opacity_name(stem, i));
}
}
}
(o, m)
}
fn gltf(stem: &str, parts: &[SolidMesh]) -> String {
let (colors, material) = materials(parts);
fn gltf(stem: &str, scene: &Scene) -> String {
let parts = scene.parts;
let (materials, material) = materials(scene);
let mut buffer: Vec<u8> = vec![];
let (mut views, mut accessors, mut primitives) = (vec![], vec![], vec![]);
let mut view = |buffer: &mut Vec<u8>, bytes: Vec<u8>, target: u32| -> usize {
@@ -154,16 +307,25 @@ fn gltf(stem: &str, parts: &[SolidMesh]) -> String {
}));
accessors.push(json!({ "bufferView": normals, "componentType": 5126, "count": count, "type": "VEC3" }));
accessors.push(json!({ "bufferView": indices, "componentType": 5125, "count": p.mesh.triangles.len() * 3, "type": "SCALAR" }));
primitives.push(json!({
let mut primitive = json!({
"attributes": { "POSITION": at, "NORMAL": at + 1 },
"indices": at + 2,
"material": material.get(k).copied().unwrap_or(0),
}));
});
// glTF's texture coordinates run down from the picture's top, as the picture's own do.
if let Some((uv, _)) = scene.texture(k).filter(|(uv, _)| uv.len() == count) {
let bytes = uv.iter().flatten().flat_map(|x| (*x as f32).to_le_bytes()).collect();
let coords = view(&mut buffer, bytes, 34962);
primitive["attributes"]["TEXCOORD_0"] = json!(accessors.len());
accessors.push(json!({ "bufferView": coords, "componentType": 5126, "count": count, "type": "VEC2" }));
}
primitives.push(primitive);
}
let materials: Vec<Value> = colors
let materials: Vec<Value> = materials
.iter()
.enumerate()
.map(|(k, c)| {
.map(|(k, mat)| {
let c = mat.color;
let mut m = json!({
"name": format!("Material_{}", k + 1),
"pbrMetallicRoughness": {
@@ -173,13 +335,18 @@ fn gltf(stem: &str, parts: &[SolidMesh]) -> String {
},
"doubleSided": true,
});
if let Some(i) = mat.image {
// The picture holds the color and the opacity; the factor multiplies them.
m["pbrMetallicRoughness"]["baseColorFactor"] = json!([1.0, 1.0, 1.0, 1.0]);
m["pbrMetallicRoughness"]["baseColorTexture"] = json!({ "index": i });
}
if c[3] < 1.0 {
m["alphaMode"] = json!("BLEND");
}
m
})
.collect();
let doc = json!({
let mut doc = json!({
"asset": { "version": "2.0", "generator": "VectorCraft" },
"scene": 0,
"scenes": [{ "nodes": [0] }],
@@ -193,6 +360,14 @@ fn gltf(stem: &str, parts: &[SolidMesh]) -> String {
"bufferViews": views,
"accessors": accessors,
});
if !scene.pictures.is_empty() {
// Linear filtering, mipmaps, and coordinates held at the picture's edge.
doc["samplers"] = json!([{ "magFilter": 9729, "minFilter": 9987, "wrapS": 33071, "wrapT": 33071 }]);
doc["textures"] = Value::Array((0..scene.pictures.len()).map(|i| json!({ "sampler": 0, "source": i })).collect());
doc["images"] = Value::Array(
scene.pictures.iter().map(|p| json!({ "uri": format!("data:image/png;base64,{}", vectorcraft_format::base64_encode(p)) })).collect(),
);
}
serde_json::to_string_pretty(&doc).unwrap_or_default()
}
@@ -205,8 +380,9 @@ fn prim_name(name: &str) -> String {
out
}
fn usda(stem: &str, parts: &[SolidMesh]) -> String {
let (colors, material) = materials(parts);
fn usda(stem: &str, scene: &Scene) -> String {
let parts = scene.parts;
let (materials, material) = materials(scene);
let root = prim_name(stem);
let triple = |v: [f64; 3]| format!("({}, {}, {})", num(v[0]), num(v[1]), num(v[2]));
let list = |items: Vec<String>| items.join(", ");
@@ -238,23 +414,178 @@ fn usda(stem: &str, parts: &[SolidMesh]) -> String {
linear(c[2])
);
let _ = writeln!(u, " float[] primvars:displayOpacity = [{}] (\n interpolation = \"constant\"\n )", c[3]);
// USD's texture coordinates run up from the picture's bottom.
if let Some((uv, _)) = scene.texture(k).filter(|(uv, _)| uv.len() == p.mesh.positions.len()) {
let st = list(uv.iter().map(|t| format!("({}, {})", num(t[0]), num(1.0 - t[1]))).collect());
let _ = writeln!(u, " texCoord2f[] primvars:st = [{st}] (\n interpolation = \"vertex\"\n )");
}
let _ = writeln!(u, " uniform token subdivisionScheme = \"none\"\n }}\n");
}
let _ = writeln!(u, " def Scope \"Materials\"\n {{");
for (k, c) in colors.iter().enumerate() {
let m = k + 1;
for (k, mat) in materials.iter().enumerate() {
let (m, c) = (k + 1, mat.color);
let at = format!("/{root}/Materials/Material_{m}");
let _ = writeln!(u, " def Material \"Material_{m}\"\n {{");
let _ = writeln!(u, " token outputs:surface.connect = </{root}/Materials/Material_{m}/Surface.outputs:surface>\n");
let _ = writeln!(u, " token outputs:surface.connect = <{at}/Surface.outputs:surface>\n");
let _ = writeln!(u, " def Shader \"Surface\"\n {{");
let _ = writeln!(u, " uniform token info:id = \"UsdPreviewSurface\"");
let _ = writeln!(u, " color3f inputs:diffuseColor = ({}, {}, {})", linear(c[0]), linear(c[1]), linear(c[2]));
let _ = writeln!(u, " float inputs:opacity = {}", c[3]);
match mat.image {
// The picture holds the color, and the opacity when the face is not opaque.
Some(_) => {
let _ = writeln!(u, " color3f inputs:diffuseColor.connect = <{at}/Texture.outputs:rgb>");
if c[3] < 1.0 {
let _ = writeln!(u, " float inputs:opacity.connect = <{at}/Texture.outputs:a>");
} else {
let _ = writeln!(u, " float inputs:opacity = 1");
}
}
None => {
let _ = writeln!(u, " color3f inputs:diffuseColor = ({}, {}, {})", linear(c[0]), linear(c[1]), linear(c[2]));
let _ = writeln!(u, " float inputs:opacity = {}", c[3]);
}
}
let _ = writeln!(u, " float inputs:roughness = 1");
let _ = writeln!(u, " token outputs:surface\n }}\n }}");
let _ = writeln!(u, " token outputs:surface\n }}");
if let Some(i) = mat.image {
let _ = writeln!(u, "\n def Shader \"Texture\"\n {{");
let _ = writeln!(u, " uniform token info:id = \"UsdUVTexture\"");
let _ = writeln!(u, " asset inputs:file = @{}@", texture_name(stem, i));
let _ = writeln!(u, " float2 inputs:st.connect = <{at}/Coordinates.outputs:result>");
let _ = writeln!(u, " token inputs:sourceColorSpace = \"sRGB\"");
let _ = writeln!(u, " token inputs:wrapS = \"clamp\"");
let _ = writeln!(u, " token inputs:wrapT = \"clamp\"");
let _ = writeln!(u, " float3 outputs:rgb");
if c[3] < 1.0 {
let _ = writeln!(u, " float outputs:a");
}
let _ = writeln!(u, " }}");
let _ = writeln!(u, "\n def Shader \"Coordinates\"\n {{");
let _ = writeln!(u, " uniform token info:id = \"UsdPrimvarReader_float2\"");
let _ = writeln!(u, " string inputs:varname = \"st\"");
let _ = writeln!(u, " float2 outputs:result\n }}");
}
let _ = writeln!(u, " }}");
}
let _ = writeln!(u, " }}\n}}");
u
}
/// The pictures of the graphics on `parts` ([`SolidMesh::graphics`]), one for each part in order
/// (`None` for a part without graphics, or whose graphics draw nothing): the part's color with its
/// graphics drawn over it, flat and unshaded ([`vectorcraft_render::effects::mesh_graphics_art`]),
/// over the bounds of the art points of its corners, `size` pixels along the longer side. Parts with
/// the same color, face, graphics and bounds share one picture. `pixels` counts the pixels drawn so
/// far, and every call of one export shares it: an error when it passes [`MAX_TEXTURE_PIXELS`].
pub(crate) fn textures(doc: &Document, parts: &[SolidMesh], size: u32, pixels: &mut u64) -> Result<Vec<Option<Texture>>, String> {
let mut renderer: Option<vectorcraft_render::Renderer> = None;
// Each picture drawn: the part it was drawn for, its bounds, and the PNG with its opacity map
// (`None`: nothing drawn).
let mut drawn: Vec<Drawn> = vec![];
let mut out = vec![];
for part in parts {
let Some(g) = &part.graphics else {
out.push(None);
continue;
};
let Some(frame) = texture_frame(g) else {
out.push(None);
continue;
};
let scale = f64::from(size) / frame.width().max(frame.height());
let fit = |side: f64| ((side * scale).ceil() as u32).clamp(1, size);
let (w, h) = (fit(frame.width()), fit(frame.height()));
let same = |(p, r, _): &&Drawn| p.color == part.color && *r == frame && p.graphics.as_ref().is_some_and(|o| same_graphics(o, g));
let png = match drawn.iter().find(same) {
Some((_, _, png)) => png.clone(),
None => {
let png = match vectorcraft_render::effects::mesh_graphics_art(doc, NodeId(0), g)? {
None => None,
Some(art) => {
*pixels = pixels.saturating_add(u64::from(w) * u64::from(h));
if *pixels > MAX_TEXTURE_PIXELS {
return Err(format!(
"the graphics need more than {MAX_TEXTURE_PIXELS} pixels of textures: lower textureSize (now {size})"
));
}
let renderer = renderer.get_or_insert_with(vectorcraft_render::Renderer::new);
Some(picture(doc, renderer, (part.color, g.opacity, g.object), art, (frame, scale), (w, h))?)
}
};
drawn.push((part, frame, png.clone()));
png
}
};
out.push(png.map(|(png, opacity)| {
let uv = g.art.iter().map(|p| [(p.x - frame.x0) * scale / f64::from(w), (p.y - frame.y0) * scale / f64::from(h)]).collect();
Texture { png, opacity, uv }
}));
}
Ok(out)
}
/// Does [`textures`] draw a picture for one of `parts`: a part with graphics whose corners span an
/// area and whose graphics draw something? Nothing is rendered.
pub fn draws_textures(doc: &Document, parts: &[SolidMesh]) -> bool {
parts.iter().any(|p| {
p.graphics
.as_ref()
.is_some_and(|g| texture_frame(g).is_some() && matches!(vectorcraft_render::effects::mesh_graphics_art(doc, NodeId(0), g), Ok(Some(_))))
})
}
/// The part of the art's plane a picture of `g` covers: the bounds of its corners' art points, when
/// they span an area.
fn texture_frame(g: &MeshGraphics) -> Option<Rect> {
g.art_bounds().filter(|r| r.width() > 1e-9 && r.height() > 1e-9 && r.width().is_finite() && r.height().is_finite())
}
/// A picture [`textures`] drew: the part, the bounds and the PNG with its opacity map.
type Drawn<'a> = (&'a SolidMesh, Rect, Option<Picture>);
/// Do `a` and `b` draw the same graphics on their face?
fn same_graphics(a: &MeshGraphics, b: &MeshGraphics) -> bool {
a.face == b.face && a.center == b.center && a.graphics == b.graphics && a.opacity == b.opacity && a.object == b.object
}
/// `art` drawn over `color` as a PNG of `w` × `h` pixels whose top left is `frame`'s top left, at
/// `scale` pixels a point, with a grayscale PNG of its alpha when some of it is not opaque. As on
/// the canvas, the art is drawn at `face` (the opacity of the face's fill or stroke), the color at
/// its own opacity without `object`'s, and `object` (the object's opacity) applies to the whole
/// picture.
fn picture(
doc: &Document,
renderer: &mut vectorcraft_render::Renderer,
(color, face, object): ([f32; 4], f32, f32),
mut art: Node,
(frame, scale): (Rect, f64),
(w, h): (u32, u32),
) -> Result<Picture, String> {
// The color reaches two pixels past the frame, so the picture's edge pixels are covered.
let reach = 2.0 / scale;
let back = Rect::new(frame.x0 - reach, frame.y0 - reach, frame.x0 + f64::from(w) / scale + reach, frame.y0 + f64::from(h) / scale + reach);
let fill = Paint::solid(Color::rgb(color[0], color[1], color[2]));
let mut ground = Node::path(NodeId(0), vectorcraft_geom::shapes::rectangle(back), Appearance::basic(fill, Paint::None, 0.0));
let unit = |v: f32| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 };
let object = unit(object);
ground.opacity = if object > 0.0 { unit(color[3] / object) } else { 0.0 };
art.opacity *= unit(face);
let mut group = Node::group(NodeId(0), vec![Arc::new(ground), Arc::new(art)]);
group.opacity = object;
let group = Arc::new(group);
let (pw, ph) = (u16::try_from(w).map_err(|_| "texture too large")?, u16::try_from(h).map_err(|_| "texture too large")?);
let view = Affine::scale(scale) * Affine::translate((-frame.x0, -frame.y0));
let drawn = renderer.render_node(doc, &group, pw, ph, view).ok_or_else(|| "the graphics could not be drawn".to_string())?;
let alpha: Vec<u8> = drawn.pixels.iter().skip(3).step_by(4).copied().collect();
let opacity = if alpha.iter().all(|a| *a == 255) {
None
} else {
let gray = image::GrayImage::from_raw(w, h, alpha).ok_or("the texture's opacity could not be drawn")?;
let mut png = vec![];
gray.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).map_err(|e| format!("PNG encoding failed: {e}"))?;
Some(Arc::new(png))
};
Ok((Arc::new(drawn.to_png()?), opacity))
}
#[cfg(test)]
mod tests;
+133 -14
View File
@@ -7,7 +7,7 @@ use super::*;
fn square(color: [f32; 4]) -> SolidMesh {
let [a, b, c, d] = [[-5.0, -5.0, 0.0], [5.0, -5.0, 0.0], [5.0, 5.0, 0.0], [-5.0, 5.0, 0.0]];
let mesh = Mesh { positions: vec![a, b, c, a, c, d], normals: vec![[0.0, 0.0, 1.0]; 6], triangles: vec![[0, 1, 2], [3, 4, 5]] };
SolidMesh { mesh, color }
SolidMesh::plain(mesh, color)
}
const RED: [f32; 4] = [1.0, 0.0, 0.0, 1.0];
@@ -18,9 +18,14 @@ fn text(files: &[(String, Vec<u8>)], name: &str) -> String {
String::from_utf8(bytes.clone()).unwrap()
}
/// [`mesh_files`] without textures.
fn plain_files(stem: &str, format: &str, parts: &[SolidMesh]) -> Result<Vec<(String, Vec<u8>)>, String> {
mesh_files(stem, format, parts, &[])
}
#[test]
fn obj_numbers_corners_across_solids_and_names_its_materials() {
let files = mesh_files("Box", "obj", &[square(RED), square(BLUE), square(RED)]).unwrap();
let files = plain_files("Box", "obj", &[square(RED), square(BLUE), square(RED)]).unwrap();
assert_eq!(files.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), ["Box.obj", "Box.mtl"]);
let obj = text(&files, "Box.obj");
assert!(obj.starts_with("mtllib Box.mtl\no Box\n"));
@@ -36,7 +41,7 @@ fn obj_numbers_corners_across_solids_and_names_its_materials() {
#[test]
fn gltf_holds_its_buffer_and_every_accessor_fits_it() {
let files = mesh_files("Box", "gltf", &[square(RED), square(BLUE)]).unwrap();
let files = plain_files("Box", "gltf", &[square(RED), square(BLUE)]).unwrap();
let g: Value = serde_json::from_str(&text(&files, "Box.gltf")).unwrap();
assert_eq!(g["asset"]["version"], "2.0");
let uri = g["buffers"][0]["uri"].as_str().unwrap();
@@ -59,11 +64,13 @@ fn gltf_holds_its_buffer_and_every_accessor_fits_it() {
assert_eq!(g["materials"][1]["alphaMode"], "BLEND");
assert!(g["materials"][0].get("alphaMode").is_none());
assert_eq!(g["materials"][0]["doubleSided"], true);
// Without graphics there are no textures.
assert!(g.get("images").is_none() && g.get("textures").is_none() && prims[0]["attributes"].get("TEXCOORD_0").is_none());
}
#[test]
fn usda_is_y_up_in_points_with_a_material_for_each_color() {
let files = mesh_files("My Box", "usda", &[square(RED), square([0.5, 0.5, 0.5, 1.0])]).unwrap();
let files = plain_files("My Box", "usda", &[square(RED), square([0.5, 0.5, 0.5, 1.0])]).unwrap();
let u = text(&files, "My Box.usda");
assert!(u.starts_with("#usda 1.0\n"));
assert!(u.contains("defaultPrim = \"My_Box\"") && u.contains("upAxis = \"Y\"") && u.contains("def Xform \"My_Box\""), "{u}");
@@ -75,11 +82,12 @@ fn usda_is_y_up_in_points_with_a_material_for_each_color() {
// sRGB 0.5 is about 0.214 linear.
assert!(u.contains("color3f inputs:diffuseColor = (0.21404"), "{u}");
assert_eq!(u.matches('{').count(), u.matches('}').count());
assert!(!u.contains("primvars:st") && !u.contains("UsdUVTexture"));
}
#[test]
fn usdz_stores_the_layer_uncompressed_on_a_64_byte_boundary() {
let files = mesh_files("Box", "usdz", &[square(RED)]).unwrap();
let files = plain_files("Box", "usdz", &[square(RED)]).unwrap();
let (name, zip) = &files[0];
assert_eq!(name, "Box.usdz");
// The local header: 30 bytes, the name, then the extra field.
@@ -88,7 +96,7 @@ fn usdz_stores_the_layer_uncompressed_on_a_64_byte_boundary() {
assert_eq!(u16_at(8), 0, "stored, not deflated");
let start = 30 + u16_at(26) + u16_at(28);
assert_eq!(start % 64, 0);
let layer = mesh_files("Box", "usda", &[square(RED)]).unwrap().remove(0).1;
let layer = plain_files("Box", "usda", &[square(RED)]).unwrap().remove(0).1;
assert_eq!(&zip[start..start + layer.len()], layer.as_slice());
let archive = super::super::zip::Archive::open(zip, 8).unwrap();
assert_eq!(archive.read("Box.usda", usize::MAX).unwrap(), Some(layer));
@@ -96,11 +104,11 @@ fn usdz_stores_the_layer_uncompressed_on_a_64_byte_boundary() {
#[test]
fn an_obj_names_its_mtl_file_without_spaces_or_comment_marks() {
let files = mesh_files("Box #1", "obj", &[square(RED)]).unwrap();
let files = plain_files("Box #1", "obj", &[square(RED)]).unwrap();
assert_eq!(files.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), ["Box__1.obj", "Box__1.mtl"]);
assert!(text(&files, "Box__1.obj").starts_with("mtllib Box__1.mtl\n"));
assert_eq!(mesh_file_names("Box #1", "obj").unwrap(), ["Box__1.obj", "Box__1.mtl"]);
assert_eq!(mesh_file_names("Box #1", "usda").unwrap(), ["Box #1.usda"]);
assert_eq!(mesh_file_names("Box #1", "obj", &[]).unwrap(), ["Box__1.obj", "Box__1.mtl"]);
assert_eq!(mesh_file_names("Box #1", "usda", &[]).unwrap(), ["Box #1.usda"]);
}
#[test]
@@ -108,17 +116,17 @@ fn obj_and_usda_keep_coordinates_a_32_bit_float_would_merge() {
let mut part = square(RED);
part.mesh.positions[0] = [20_000_000.0, 0.0, 0.0];
part.mesh.positions[1] = [20_000_001.0, 0.0, 0.0];
let obj = text(&mesh_files("Box", "obj", std::slice::from_ref(&part)).unwrap(), "Box.obj");
let obj = text(&plain_files("Box", "obj", std::slice::from_ref(&part)).unwrap(), "Box.obj");
assert!(obj.contains("v 20000000 0 0\nv 20000001 0 0\n"), "{obj}");
let usda = text(&mesh_files("Box", "usda", &[part]).unwrap(), "Box.usda");
let usda = text(&plain_files("Box", "usda", &[part]).unwrap(), "Box.usda");
assert!(usda.contains("(20000001, 0, 0)"));
}
#[test]
fn an_unknown_format_is_refused() {
assert!(mesh_files("Box", "fbx", &[square(RED)]).is_err());
assert!(mesh_file_names("Box", "").is_err());
assert_eq!(mesh_file_names("Box", "obj").unwrap(), ["Box.obj", "Box.mtl"]);
assert!(plain_files("Box", "fbx", &[square(RED)]).is_err());
assert!(mesh_file_names("Box", "", &[]).is_err());
assert_eq!(mesh_file_names("Box", "obj", &[]).unwrap(), ["Box.obj", "Box.mtl"]);
}
#[test]
@@ -128,3 +136,114 @@ fn prim_names_are_usd_identifiers() {
assert_eq!(prim_name(""), "_");
assert_eq!(prim_name("é/x"), "__x");
}
/// A red square, then a blue one whose corners show picture `png` (u to the right, v down).
fn textured(png: &[u8]) -> (Vec<SolidMesh>, Vec<Option<Texture>>) {
let uv = vec![[0.0, 1.0], [1.0, 1.0], [1.0, 0.0], [0.0, 1.0], [1.0, 0.0], [0.0, 0.0]];
let texture = Texture { png: Arc::new(png.to_vec()), opacity: None, uv };
(vec![square(RED), square(BLUE)], vec![None, Some(texture)])
}
#[test]
fn each_format_carries_a_textured_part_with_its_coordinates_and_picture() {
let png = b"\x89PNG picture".to_vec();
let (parts, pictures) = textured(&png);
// OBJ: vt runs up from the picture's bottom, the textured faces name it, and map_Kd the PNG
// written beside it, with its name in one word.
let files = mesh_files("My Box", "obj", &parts, &pictures).unwrap();
assert_eq!(files.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), ["My_Box.obj", "My_Box.mtl", "My_Box-texture-1.png"]);
assert_eq!(files[2].1, png);
let obj = text(&files, "My_Box.obj");
assert_eq!(obj.lines().filter(|l| l.starts_with("vt ")).collect::<Vec<_>>(), ["vt 0 0", "vt 1 0", "vt 1 1", "vt 0 0", "vt 1 1", "vt 0 1"]);
assert_eq!(obj.lines().rfind(|l| l.starts_with("f ")), Some("f 10/4/10 11/5/11 12/6/12"));
assert!(obj.contains("f 1//1 2//2 3//3"), "the plain part keeps no texture coordinates");
let mtl = text(&files, "My_Box.mtl");
assert!(mtl.contains("newmtl Material_2\nKd 1 1 1\nd 1\nillum 1\nmap_Kd -clamp on My_Box-texture-1.png\n"), "{mtl}");
assert_eq!(mtl.matches("map_Kd").count(), 1);
// glTF: TEXCOORD_0 down from the top, and the picture embedded as a data URI.
let g: Value = serde_json::from_str(&text(&mesh_files("Box", "gltf", &parts, &pictures).unwrap(), "Box.gltf")).unwrap();
let prims = g["meshes"][0]["primitives"].as_array().unwrap();
assert!(prims[0]["attributes"].get("TEXCOORD_0").is_none());
let uv = &g["accessors"][prims[1]["attributes"]["TEXCOORD_0"].as_u64().unwrap() as usize];
assert_eq!((uv["type"].as_str(), uv["count"].as_u64(), uv["componentType"].as_u64()), (Some("VEC2"), Some(6), Some(5126)));
let view = &g["bufferViews"][uv["bufferView"].as_u64().unwrap() as usize];
let data = vectorcraft_format::base64_decode(g["buffers"][0]["uri"].as_str().unwrap().split(',').nth(1).unwrap()).unwrap();
let at = view["byteOffset"].as_u64().unwrap() as usize;
let first: Vec<f32> = (0..2).map(|k| f32::from_le_bytes(data[at + 4 * k..at + 4 * k + 4].try_into().unwrap())).collect();
assert_eq!(first, [0.0, 1.0]);
let material = &g["materials"][prims[1]["material"].as_u64().unwrap() as usize];
assert_eq!(material["pbrMetallicRoughness"]["baseColorTexture"]["index"], 0);
assert_eq!(material["pbrMetallicRoughness"]["baseColorFactor"], serde_json::json!([1.0, 1.0, 1.0, 1.0]));
assert_eq!(g["textures"][0]["source"], 0);
assert_eq!(g["samplers"][0]["wrapS"], 33071);
let image = g["images"][0]["uri"].as_str().unwrap().strip_prefix("data:image/png;base64,").unwrap();
assert_eq!(vectorcraft_format::base64_decode(image).unwrap(), png);
// USDA: st up from the bottom, read by a primvar reader into a UV texture of the PNG beside it.
let files = mesh_files("Box", "usda", &parts, &pictures).unwrap();
assert_eq!(files.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), ["Box.usda", "Box-texture-1.png"]);
let u = text(&files, "Box.usda");
assert_eq!(u.matches("primvars:st").count(), 1);
assert!(u.contains("texCoord2f[] primvars:st = [(0, 0), (1, 0), (1, 1), (0, 0), (1, 1), (0, 1)]"), "{u}");
assert!(u.contains("color3f inputs:diffuseColor.connect = </Box/Materials/Material_2/Texture.outputs:rgb>"), "{u}");
assert!(u.contains("asset inputs:file = @Box-texture-1.png@") && u.contains("uniform token info:id = \"UsdUVTexture\""));
assert!(u.contains("float2 inputs:st.connect = </Box/Materials/Material_2/Coordinates.outputs:result>"));
assert!(u.contains("string inputs:varname = \"st\""));
assert_eq!(u.matches('{').count(), u.matches('}').count());
// USDZ: the layer first, then the picture, each on a 64-byte boundary.
let zip = mesh_files("Box", "usdz", &parts, &pictures).unwrap().remove(0).1;
let archive = super::super::zip::Archive::open(&zip, 8).unwrap();
assert_eq!(archive.read("Box.usda", usize::MAX).unwrap().map(String::from_utf8), Some(Ok(u)));
assert_eq!(archive.read("Box-texture-1.png", usize::MAX).unwrap(), Some(png.clone()));
let u16_at = |at: usize| u16::from_le_bytes([zip[at], zip[at + 1]]) as usize;
let u32_at = |at: usize| u32::from_le_bytes([zip[at], zip[at + 1], zip[at + 2], zip[at + 3]]) as usize;
let first = 30 + u16_at(26) + u16_at(28);
let second = first + u32_at(18);
assert_eq!(&zip[second..second + 4], &[0x50, 0x4b, 0x03, 0x04], "the picture comes second");
let data = second + 30 + u16_at(second + 26) + u16_at(second + 28);
assert_eq!((first % 64, data % 64), (0, 0));
assert_eq!(&zip[data..data + png.len()], png.as_slice());
}
#[test]
fn a_textured_face_that_is_not_opaque_takes_its_opacity_from_the_picture() {
let (parts, mut pictures) = textured(b"picture");
if let Some(t) = pictures[1].as_mut() {
t.opacity = Some(Arc::new(b"gray".to_vec()));
}
// OBJ: the opacity map, written after its texture, is the MTL's map_d.
let files = mesh_files("My Box", "obj", &parts, &pictures).unwrap();
let names: Vec<&str> = files.iter().map(|(n, _)| n.as_str()).collect();
assert_eq!(names, ["My_Box.obj", "My_Box.mtl", "My_Box-texture-1.png", "My_Box-texture-1-opacity.png"]);
assert_eq!(files[3].1, b"gray");
assert_eq!(mesh_file_names("My Box", "obj", &image_maps(&pictures)).unwrap(), names);
let mtl = text(&files, "My_Box.mtl");
assert!(mtl.contains("d 1\nillum 1\nmap_Kd -clamp on My_Box-texture-1.png\nmap_d -clamp on My_Box-texture-1-opacity.png\n"), "{mtl}");
let g: Value = serde_json::from_str(&text(&mesh_files("Box", "gltf", &parts, &pictures).unwrap(), "Box.gltf")).unwrap();
let material = &g["materials"][1];
assert_eq!((material["pbrMetallicRoughness"]["baseColorFactor"][3].as_f64(), material["alphaMode"].as_str()), (Some(1.0), Some("BLEND")));
let usda = mesh_files("Box", "usda", &parts, &pictures).unwrap();
assert_eq!(usda.len(), 2, "USD reads the opacity from the texture's alpha");
let u = text(&usda, "Box.usda");
assert!(u.contains("float inputs:opacity.connect = </Box/Materials/Material_2/Texture.outputs:a>") && u.contains("float outputs:a"), "{u}");
// An opaque textured face reads no opacity from its picture.
let (_, plain) = textured(b"picture");
let opaque = vec![square(RED), square([0.0, 0.0, 1.0, 1.0])];
let u = text(&mesh_files("Box", "usda", &opaque, &plain).unwrap(), "Box.usda");
assert!(!u.contains("outputs:a") && u.contains("float inputs:opacity = 1"), "{u}");
let mtl = text(&mesh_files("Box", "obj", &opaque, &plain).unwrap(), "Box.mtl");
assert!(!mtl.contains("map_d") && mtl.contains("Kd 1 1 1\nd 1\n"), "{mtl}");
}
#[test]
fn parts_sharing_a_picture_write_it_once() {
let (mut parts, mut pictures) = textured(b"one");
parts.push(square(BLUE));
pictures.push(pictures[1].clone());
assert_eq!(image_maps(&pictures), [false]);
let files = mesh_files("Box", "obj", &parts, &pictures).unwrap();
assert_eq!(files.len(), 3);
assert_eq!(text(&files, "Box.mtl").matches("newmtl").count(), 2, "the blue parts share the textured material");
assert_eq!(mesh_file_names("Box", "usda", &[false, true]).unwrap(), ["Box.usda", "Box-texture-1.png", "Box-texture-2.png"]);
assert_eq!(mesh_file_names("A @b", "gltf", &[false, false]).unwrap(), ["A @b.gltf"]);
assert_eq!(texture_name("A @b#c", 0), "A__b_c-texture-1.png");
}
+42
View File
@@ -500,6 +500,48 @@ pub(super) fn to_rgb(h: &Header<'_>, v: impl Fn(usize) -> f32, cmyk: &impl Fn([f
}
}
/// An opaque CMYK composite as its original 8- or 16-bit ink samples. Other modes,
/// composites with transparency, and images beyond the native CMYK pixel or allocation limit return `None`.
pub(super) fn decode_cmyk(bytes: &[u8], max_alloc: u64) -> Result<Option<craft_image_codecs::Image>, String> {
use craft_image_codecs::{ChannelLayout, Image, SampleType};
let mut r = Reader::new(bytes);
let h = header(&mut r)?;
if h.mode != Mode::Cmyk || (h.channels > 4 && merged_alpha(h.layers, h.psb)) {
return Ok(None);
}
let pixels = u64::from(h.width) * u64::from(h.height);
if pixels > vectorcraft_doc::cmyk::MAX_CMYK_PIXELS {
return Ok(None);
}
let sample_bytes = usize::from(h.depth / 8);
let samples = pixels * 4 * sample_bytes as u64;
let icc = resources(h.resources, false)
.find(|(id, _, _)| *id == 1039)
.map(|(_, _, data)| data)
.filter(|data| data.len() <= 16 << 20 && vectorcraft_doc::cmyk::icc_color_space(data) == Some(*b"CMYK"));
if samples.saturating_mul(2).saturating_add(icc.map_or(0, |p| p.len() as u64)) > max_alloc {
return Ok(None);
}
let count = pixels as usize;
let data = channel_data(r.rest(), &h, 4, row_bytes(h.width as usize, h.depth))?;
let mut out = Vec::with_capacity(samples as usize);
for i in 0..count {
for channel in 0..4 {
let at = (channel * count + i) * sample_bytes;
if h.depth == 8 {
out.push(255 - data.get(at).copied().ok_or(TRUNCATED)?);
} else {
let pair = data.get(at..at + 2).ok_or(TRUNCATED)?.try_into().map_err(|_| TRUNCATED)?;
out.extend((65535 - u16::from_be_bytes(pair)).to_ne_bytes());
}
}
}
let sample = if h.depth == 16 { SampleType::U16 } else { SampleType::U8 };
let mut image = Image::from_raw(h.width, h.height, ChannelLayout::Cmyk, sample, out).map_err(|e| e.to_string())?;
image.icc = icc.map(<[u8]>::to_vec);
Ok(Some(image))
}
/// A Photoshop document's merged image as straight RGBA. CMYK converts through `cmyk` (ink
/// amounts 0..1 → sRGB). Fails, without allocating, when the image would need more than
/// `max_alloc` bytes.
@@ -97,6 +97,132 @@ fn every_colour_mode_and_depth_reads() {
assert_eq!(pixels(&psd(1, 1, (1, 1), 8, 8, &[0; 40], &[], &[], &raw(&[&[64]]))), [[64, 64, 64, 255]]);
}
#[test]
fn cmyk_psd_place_keeps_the_native_ink_samples() {
let f = psd(1, 4, (2, 1), 8, 4, &[], &[], &[], &raw(&[&[191, 255], &[127, 0], &[63, 127], &[223, 0]]));
let p = json!({"name": "inks.psd", "dataBase64": vectorcraft_format::base64_encode(&f)});
let mut s = Session::new();
s.execute("file.new", &json!({"width": 40, "height": 20})).unwrap();
let info = s.execute("file.place.info", &p).unwrap();
assert_eq!(info["colorMode"], "CMYK");
let placed = s.execute("file.place", &p).unwrap();
let id = NodeId(placed["ids"][0].as_u64().unwrap());
let d = &s.doc().unwrap().doc;
let NodeKind::Image(im) = &d.node(id).unwrap().kind else { panic!("placed PSD is an image") };
let blob = d.images.get(&im.key).unwrap();
assert!(blob.is_cmyk());
assert_eq!(blob.cmyk().unwrap().data, [64, 128, 192, 32, 0, 255, 128, 255]);
}
#[test]
fn cmyk_psd_native_budget_keeps_the_rgba_fallback_available() {
let bytes = psd(1, 4, (2, 1), 16, 4, &[], &[], &[], &raw(&[&[0xff; 4], &[0xff; 4], &[0xff; 4], &[0; 4]]));
assert!(super::psdread::decode_cmyk(&bytes, 24).unwrap().is_none());
assert_eq!(decode(&bytes, 24, naive).unwrap().into_raw(), [0, 0, 0, 255, 0, 0, 0, 255]);
assert!(decode(&bytes, 1, naive).is_err());
}
#[test]
fn cmyk_psd_depth_and_compression_preserve_exact_samples() {
for version in [1, 2] {
for depth in [8, 16] {
let values = if depth == 8 { [191u16, 127, 63, 223] } else { [0xcdef, 0x89ab, 0x4567, 0x0123] };
let planes: Vec<Vec<u8>> = values.iter().map(|v| if depth == 8 { vec![*v as u8] } else { v.to_be_bytes().to_vec() }).collect();
let uncompressed = planes.concat();
for method in 0..=3u16 {
let mut data = method.to_be_bytes().to_vec();
match method {
0 => data.extend(&uncompressed),
1 => {
for p in &planes {
let count = (p.len() + 1) as u32;
if version == 2 { data.extend(count.to_be_bytes()) } else { data.extend((count as u16).to_be_bytes()) }
}
for p in &planes {
data.push((p.len() - 1) as u8);
data.extend(p);
}
}
_ => {
// One sample per row has the same bytes with or without prediction.
let mut z = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default());
std::io::Write::write_all(&mut z, &uncompressed).unwrap();
data.extend(z.finish().unwrap());
}
}
let bytes = psd(version, 4, (1, 1), depth, 4, &[], &[], &[], &data);
let img = raster_image(&bytes).unwrap();
assert!(img.blob.is_cmyk(), "version {version}, depth {depth}, compression {method}");
assert_eq!(img.blob.is_cmyk16(), depth == 16);
let decoded = craft_image_codecs::decode(&img.blob.bytes).unwrap();
let expected: Vec<u8> =
values.iter().flat_map(|v| if depth == 8 { vec![255 - *v as u8] } else { (65535 - v).to_ne_bytes().to_vec() }).collect();
assert_eq!(decoded.data(), expected);
assert!(super::psdread::decode_cmyk(&bytes, 1).unwrap().is_none());
assert!(super::psdread::decode_cmyk(&bytes[..bytes.len() - data.len() + 2], 1 << 30).is_err());
}
}
}
let planes: [&[u8]; 5] = [&[255], &[255], &[255], &[255], &[128]];
let saved = psd(1, 5, (1, 1), 8, 4, &[], &[], &[], &raw(&planes));
assert!(raster_image(&saved).unwrap().blob.is_cmyk(), "a saved selection is not transparency");
let alpha = psd(1, 5, (1, 1), 8, 4, &[], &[], &layer_count(-1, false), &raw(&planes));
let img = raster_image(&alpha).unwrap();
assert!(!img.blob.is_cmyk());
assert_eq!(craft_image_codecs::decode(&img.blob.bytes).unwrap().to_rgba8()[3], 128);
}
#[test]
fn cmyk_psd_links_keep_inks_profile_resolution_and_clipping() {
let profile = vectorcraft_color::cms::icc_bytes(vectorcraft_color::cms::GENERIC_CMYK).unwrap();
let mut res = Vec::new();
res.extend((144u32 << 16).to_be_bytes());
res.extend([0, 1, 0, 1]);
res.extend((144u32 << 16).to_be_bytes());
res.extend([0, 1, 0, 1]);
let make = |clip: &[u8], ink: u8| {
let resources = [resource(1039, b"", &profile), resource(1005, b"", &res), clip.to_vec()].concat();
psd(1, 4, (2, 1), 8, 4, &[], &resources, &[], &raw(&[&[255 - ink; 2], &[127; 2], &[63; 2], &[223; 2]]))
};
let dir = vectorcraft_testkit::TempDir::new("psd-cmyk-links");
let cut = write_file(&dir, "cut.psd", &make(&triangle_resources(), 64));
let square = write_file(&dir, "square.psd", &make(&square_resources(), 96));
let mut s = Session::new();
s.execute("file.new", &json!({"width": 20, "height": 10, "colorMode": "cmyk"})).unwrap();
assert_eq!(s.execute("file.place.info", &json!({"path": cut})).unwrap()["colorMode"], "CMYK");
let r = s.execute("file.place", &json!({"path": cut, "at": [0.5, 0.25]})).unwrap();
let group = NodeId(r["ids"][0].as_u64().unwrap());
let id = r["image"].as_u64().unwrap();
assert_eq!(r["width"], 1.0);
assert_eq!(r["height"], 0.5);
let check = |s: &mut Session, ink, linked| {
let info = s.execute("links.info", &json!({"id": id})).unwrap();
assert_eq!(info["colorMode"], "CMYK");
assert_eq!(info["linked"], linked);
assert_eq!(info["ppi"], json!([144.0, 144.0]));
let d = &s.doc().unwrap().doc;
let NodeKind::Image(im) = &d.node(NodeId(id)).unwrap().kind else { panic!("placed image") };
let blob = d.images.get(&im.key).unwrap();
assert_eq!(blob.cmyk().unwrap().data, [ink, 128, 192, 32, ink, 128, 192, 32]);
assert_eq!(blob.cmyk_icc_profile().as_deref(), Some(profile.as_ref()));
assert_eq!(
super::load::image_clip(blob),
Some(clipping_path(&make(&if ink == 64 { triangle_resources() } else { square_resources() }, ink)).unwrap())
);
};
check(&mut s, 64, true);
let triangle = clip_group(&s.doc().unwrap().doc, group);
s.execute("links.relink", &json!({"ids": [id], "path": square})).unwrap();
check(&mut s, 96, true);
assert_ne!(clip_group(&s.doc().unwrap().doc, group).0, triangle.0);
std::fs::write(&square, make(&triangle_resources(), 64)).unwrap();
s.execute("links.update", &json!({"ids": [id]})).unwrap();
check(&mut s, 64, true);
assert_eq!(clip_group(&s.doc().unwrap().doc, group), triangle);
s.execute("links.embed", &json!({"ids": [id]})).unwrap();
check(&mut s, 64, false);
}
#[test]
fn transparency_comes_back_straight_and_extra_channels_without_it_stay_out() {
// Half-transparent red, stored on white: (255, 127, 127) with alpha 128.
+39 -1
View File
@@ -4,7 +4,7 @@
use std::sync::Arc;
use serde_json::json;
use vectorcraft_doc::Document;
use vectorcraft_doc::{Document, Node, NodeKind};
use super::*;
@@ -212,6 +212,44 @@ fn a_chosen_artboard_s_svg_keeps_nested_brush_art_but_not_unpainted_or_clipped_a
assert!(kept.node(compounds[1]).is_some(), "a compound path that is brushed itself");
}
/// The art over an artboard, among 300 instances with drop shadows and 2,000 symbols, is found
/// reading the symbol list once, and keeps the instances over it.
#[test]
fn art_over_an_artboard_reads_the_symbol_list_once() {
let mut d = Document::new(100.0, 100.0);
let square = |d: &mut Document, side: f64| {
let r = vectorcraft_geom::Rect::new(-side, -side, side, side);
let ap =
vectorcraft_doc::Appearance::basic(vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), vectorcraft_color::Paint::None, 0.0);
Arc::new(Node::path(d.alloc_id(), vectorcraft_geom::shapes::rectangle(r), ap))
};
for i in 0..2000 {
let art = square(&mut d, 0.5);
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: format!("Filler {i}"), art });
}
let art = square(&mut d, 2.0);
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Mark".into(), art });
let layer = d.layers[0].id;
// Twenty rows of 15: the first ten over the artboard, the rest below it.
let ids: Vec<_> = (0..300)
.map(|i| {
let xf = vectorcraft_geom::Affine::translate((f64::from(i % 15) * 6.0 + 5.0, f64::from(i / 15) * 10.0 + 5.0));
let mut n = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Mark".into(), xf });
n.appearance.effects.push(vectorcraft_doc::Effect {
id: "stylize.dropShadow".into(),
params: json!({"x": 1, "y": 1, "blur": 0}),
visible: true,
});
d.insert(Some(layer), usize::MAX, n).unwrap()
})
.collect();
let before = vectorcraft_doc::symbols_read();
let kept = export::art_over(&d, d.artboards[0].rect, &mut vectorcraft_render::Renderer::new());
let read = vectorcraft_doc::symbols_read() - before;
assert!(read <= d.symbols.len(), "{read} symbols read, {} in the document", d.symbols.len());
assert_eq!(ids.iter().filter(|id| kept.node(**id).is_some()).count(), 150);
}
/// #3544: an SVG of one artboard on its own (an `artboard` or `range`, Export for Screens, an asset)
/// has the artboard's (or asset's) name as `<title>`; Save's SVG and Export for Screens' Full
/// Document keep the document's.
+55 -9
View File
@@ -247,10 +247,11 @@ impl Resources {
fn expand(&mut self, d: &Document) {
let mut symbols: Vec<String> = self.symbols.iter().cloned().collect();
let mut patterns: Vec<String> = self.patterns.iter().cloned().collect();
let boxes = d.symbol_boxes();
while !symbols.is_empty() || !patterns.is_empty() {
let mut more = Resources::default();
for name in symbols.drain(..) {
if let Some(sym) = d.symbols.iter().find(|sym| sym.name == name) {
if let Some(sym) = boxes.symbol(&name) {
more.add(&sym.art);
}
}
@@ -511,7 +512,7 @@ pub(super) fn art_fonts(d: &Document, art: &[Node]) -> BTreeSet<UsedFont> {
/// art of a placed document (`d` as [`Document::with_placed_art`] gives it, for that art's
/// resources).
pub(super) fn printed_type(d: &Document, layers: &[Arc<Node>], areas: &[Rect]) -> (BTreeSet<UsedFont>, BTreeSet<NodeId>) {
let mut walk = Printed { d, own: true, fonts: BTreeSet::new(), overflow: BTreeSet::new(), symbols: BTreeSet::new(), patterns: BTreeSet::new() };
let mut walk = Printed::new(d);
for l in layers {
walk.node(l, Some(areas));
}
@@ -523,7 +524,7 @@ pub(super) fn printed_type(d: &Document, layers: &[Arc<Node>], areas: &[Rect]) -
/// found as [`printed_type`] finds them for Print: visible objects of the document that aren't on
/// a template layer.
pub(super) fn export_overflow_warning(d: &Document, layers: &[Arc<Node>], areas: Option<&[Rect]>) -> Option<String> {
let mut walk = Printed { d, own: true, fonts: BTreeSet::new(), overflow: BTreeSet::new(), symbols: BTreeSet::new(), patterns: BTreeSet::new() };
let mut walk = Printed::new(d);
for l in layers {
walk.node(l, areas);
}
@@ -534,6 +535,9 @@ pub(super) fn export_overflow_warning(d: &Document, layers: &[Arc<Node>], areas:
/// The walk of [`printed_type`].
struct Printed<'a> {
d: &'a Document,
/// `d`'s symbols, found by name. Each object is measured in boxes of its own made from these
/// ([`vectorcraft_doc::SymbolBoxes::unmeasured`]).
boxes: vectorcraft_doc::SymbolBoxes<'a>,
/// Whether the walk is among the objects of the document, not in art drawn for one.
own: bool,
fonts: BTreeSet<UsedFont>,
@@ -544,7 +548,13 @@ struct Printed<'a> {
patterns: BTreeSet<String>,
}
impl Printed<'_> {
impl<'a> Printed<'a> {
/// A walk of `d` among its own objects, nothing found yet.
fn new(d: &'a Document) -> Self {
let boxes = d.symbol_boxes();
Self { d, boxes, own: true, fonts: BTreeSet::new(), overflow: BTreeSet::new(), symbols: BTreeSet::new(), patterns: BTreeSet::new() }
}
/// Adds the fonts of `n` and its descendants that print, and the ids of those that don't fit
/// while [`Printed::own`] is set: those whose bounds meet one of `areas`, or with `None` (in the
/// art of a symbol, opacity mask, pattern or placed document, in brush pieces, or in a live
@@ -625,7 +635,7 @@ impl Printed<'_> {
let clipped = match (clip, areas) {
(false, _) => None,
(true, Some(a)) => Some(self.clip(n, a)),
(true, None) => vectorcraft_render::painted_bounds(self.d, n).map(|c| vec![c]),
(true, None) => vectorcraft_render::painted_bounds_with(&self.boxes.unmeasured(), n).map(|c| vec![c]),
};
for c in children {
self.node(c, clipped.as_deref().or(areas));
@@ -641,9 +651,8 @@ impl Printed<'_> {
/// Adds the fonts of symbol `name`'s art, the first time it is shown.
fn symbol(&mut self, name: &str) {
let d = self.d;
if self.symbols.insert(name.to_string())
&& let Some(s) = d.symbols.iter().find(|s| s.name == name)
&& let Some(s) = self.boxes.symbol(name)
{
self.art(&s.art);
}
@@ -660,12 +669,13 @@ impl Printed<'_> {
/// Whether what `n` paints, its effects applied, meets one of `areas`.
fn meets(&self, n: &Node, areas: &[Rect]) -> bool {
vectorcraft_render::painted_bounds(self.d, n).is_some_and(|b| areas.iter().any(|r| b.intersect(*r).area() > 0.0 || r.contains_rect(b)))
vectorcraft_render::painted_bounds_with(&self.boxes.unmeasured(), n)
.is_some_and(|b| areas.iter().any(|r| b.intersect(*r).area() > 0.0 || r.contains_rect(b)))
}
/// The parts of `areas` inside the bounds of clip group `n` (its clipping path's).
fn clip(&self, n: &Node, areas: &[Rect]) -> Vec<Rect> {
let Some(c) = vectorcraft_render::painted_bounds(self.d, n) else { return areas.to_vec() };
let Some(c) = vectorcraft_render::painted_bounds_with(&self.boxes.unmeasured(), n) else { return areas.to_vec() };
areas.iter().filter(|r| c.intersect(**r).area() > 0.0 || r.contains_rect(c)).map(|r| r.intersect(c)).collect()
}
}
@@ -2378,4 +2388,40 @@ mod dirty_tests {
s.execute("edit.undo", &json!({})).unwrap();
assert!(!s.doc().unwrap().is_dirty(), "back to the saved state");
}
/// The walk Print and the exports make over 300 instances with drop shadows, among 2,000
/// symbols, reads the symbol list once to find their symbols.
#[test]
fn printed_type_reads_the_symbol_list_once() {
let mut d = Document::new(200.0, 200.0);
for i in 0..2000 {
let art = Node::path(
d.alloc_id(),
vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 1.0, 1.0)),
vectorcraft_doc::Appearance::basic(Paint::None, Paint::None, 0.0),
);
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: format!("Filler {i}"), art: Arc::new(art) });
}
let art = Node::path(
d.alloc_id(),
vectorcraft_geom::shapes::rectangle(Rect::new(-10.0, -10.0, 10.0, 10.0)),
vectorcraft_doc::Appearance::basic(Paint::solid(vectorcraft_color::Color::BLACK), Paint::None, 0.0),
);
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Mark".into(), art: Arc::new(art) });
let l = d.layers[0].id;
for i in 0..300 {
let xf = vectorcraft_geom::Affine::translate((f64::from(i % 20) * 10.0, f64::from(i / 20) * 10.0));
let mut n = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Mark".into(), xf });
n.appearance.effects.push(vectorcraft_doc::Effect {
id: "stylize.dropShadow".into(),
params: json!({"x": 1, "y": 1, "blur": 0}),
visible: true,
});
d.insert(Some(l), usize::MAX, n).unwrap();
}
let before = vectorcraft_doc::symbols_read();
printed_type(&d, &d.layers, &[Rect::new(0.0, 0.0, 100.0, 100.0)]);
let read = vectorcraft_doc::symbols_read() - before;
assert!(read <= d.symbols.len(), "{read} symbols read, {} in the document", d.symbols.len());
}
}
+2 -2
View File
@@ -713,12 +713,12 @@ type FileClip = (PathData, FillRule);
/// The clipping path the file of image content `blob` draws it through, in its pixel space, as it
/// was kept when the file was read: a DCS file's ([`ImageBlob::separated_clip`]) or a PSD or PSB
/// file's ([`fileio::png_clip`]).
/// file's ([`fileio::image_clip`]).
fn file_clip(blob: &ImageBlob) -> Option<FileClip> {
if let Some(path) = blob.separated_clip() {
return Some((path, FillRule::NonZero));
}
(blob.mime == "image/png").then(|| fileio::png_clip(&blob.bytes)).flatten().map(|path| (path, FillRule::EvenOdd))
fileio::image_clip(blob).map(|path| (path, FillRule::EvenOdd))
}
/// What happens to the clip of an object a link update remakes.
+20 -2
View File
@@ -357,6 +357,7 @@ pub(super) fn isolate(s: &mut Session, p: &Value) -> Result<Value> {
&& prev != isolation
{
crate::cmd::settle_interaction(s)?;
add_drawn_live_paint(s, prev, Some(isolation))?;
let st = s.doc_mut()?;
crate::cmd::distortcmds::finish_edit_text(st, prev);
}
@@ -369,6 +370,19 @@ pub(super) fn isolate(s: &mut Session, p: &Value) -> Result<Value> {
ok()
}
/// Leaving isolation mode in `isolated` for `next` (None: out of isolation mode) adds the paths drawn
/// in the Live Paint group isolation put new art in to that group, as `livePaint.merge` does, in one
/// undo step ([`crate::cmd::buildcmds::merge_drawn_in_isolation`]), unless `next` is that group or is
/// inside it; → the group when paths were added.
fn add_drawn_live_paint(s: &mut Session, isolated: NodeId, next: Option<NodeId>) -> Result<Option<NodeId>> {
let d = &s.doc()?.doc;
let Some(g) = crate::cmd::buildcmds::isolated_live_paint(d, isolated) else { return Ok(None) };
if next.is_some_and(|n| d.ancestry(n).is_some_and(|a| a.contains(&g))) {
return Ok(None);
}
Ok(crate::cmd::buildcmds::merge_drawn_in_isolation(s, g)?.then_some(g))
}
pub(super) fn exit_isolation(s: &mut Session, p: &Value) -> Result<Value> {
// Opacity mask editing, pattern editing and symbol editing isolate their editing layer. Leaving
// isolation mode then leaves that mode, as Stop Editing Opacity Mask and the isolation bar's
@@ -378,10 +392,11 @@ pub(super) fn exit_isolation(s: &mut Session, p: &Value) -> Result<Value> {
&& let Some(inner) = st.isolation.filter(|i| *i != layer && st.doc.ancestry(*i).is_some_and(|a| a.contains(&layer)))
{
crate::cmd::settle_interaction(s)?;
let left = add_drawn_live_paint(s, inner, Some(layer))?.unwrap_or(inner);
let st = s.doc_mut()?;
crate::cmd::distortcmds::finish_edit_text(st, inner);
st.isolation = Some(layer);
st.selection.set([inner]);
st.selection.set([left]);
st.revision += 1;
return ok();
}
@@ -396,6 +411,8 @@ pub(super) fn exit_isolation(s: &mut Session, p: &Value) -> Result<Value> {
};
if let Some(leave_mode) = leave_mode {
if let Some(i) = st.isolation {
crate::cmd::settle_interaction(s)?;
add_drawn_live_paint(s, i, None)?;
crate::cmd::distortcmds::finish_edit_text(s.doc_mut()?, i);
}
leave_mode(s, p)?;
@@ -405,10 +422,11 @@ pub(super) fn exit_isolation(s: &mut Session, p: &Value) -> Result<Value> {
let prev = s.active().and_then(|d| d.isolation);
if let Some(i) = prev {
crate::cmd::settle_interaction(s)?;
let left = add_drawn_live_paint(s, i, None)?.unwrap_or(i);
let st = s.doc_mut()?;
st.isolation = None;
crate::cmd::distortcmds::finish_edit_text(st, i);
let target = st.doc.parent_of(i).filter(|p| st.doc.node(*p).is_some_and(|n| n.extras().shaper.is_some())).unwrap_or(i);
let target = st.doc.parent_of(left).filter(|p| st.doc.node(*p).is_some_and(|n| n.extras().shaper.is_some())).unwrap_or(left);
st.selection.set([target]);
// A guide path isolated while Lock Guides is on isn't selected (#1534).
crate::deselect_hidden(&menu, &st.doc, &mut st.selection);
+10 -2
View File
@@ -56,6 +56,7 @@ pub(crate) fn object_bounds_transform(s: &Session, p: &Value, id: NodeId) -> Res
/// direct-selected anchors are what changes ([`Bounds::Anchors`]).
fn bounds_transform(s: &Session, p: &Value, ids: Vec<NodeId>, least: f64, anchors: bool) -> Result<Bounds> {
check_numbers(p, &["x", "y", "width", "height", "reference"], "object.setBounds")?;
let refi = reference_index(p)?;
let st = s.doc()?;
check_switches(p, &TRANSFORM_SWITCHES, "object.setBounds")?;
check_switches(p, &["proportional"], "object.setBounds")?;
@@ -90,7 +91,6 @@ fn bounds_transform(s: &Session, p: &Value, ids: Vec<NodeId>, least: f64, anchor
let margins = |b: Rect| [g.x0 - b.x0, g.y0 - b.y0, b.x1 - g.x1, b.y1 - g.y1];
let (m, all) = (margins(vs), margins(v));
let fixed = [all[0] - m[0], all[1] - m[1], all[2] - m[2], all[3] - m[3]];
let refi = p.get("reference").and_then(Value::as_u64).unwrap_or(4).min(8) as usize;
let rp = vectorcraft_geom::reference_point(v, refi);
let (w, h) = wanted_size(p, v);
// The geometric scale that gives the visual size: margins grow by the strokes' scale `f`. It is
@@ -262,7 +262,7 @@ fn wanted_size(p: &Value, b: Rect) -> (f64, f64) {
/// `b`, the box around the anchors (and the objects selected whole) square to the page, and only
/// the anchors, their handles with them, and those objects move or scale.
fn set_anchor_bounds(s: &mut Session, p: &Value, ids: Vec<NodeId>, b: Rect) -> Result<Value> {
let refi = p.get("reference").and_then(Value::as_u64).unwrap_or(4).min(8) as usize;
let refi = reference_index(p)?;
let rp = vectorcraft_geom::reference_point(b, refi);
let (w, h) = wanted_size(p, b);
// A single anchor, or anchors in a line, have no size to scale on that side.
@@ -272,6 +272,14 @@ fn set_anchor_bounds(s: &mut Session, p: &Value, ids: Vec<NodeId>, b: Rect) -> R
apply_transform(s, "Transform", ids, Affine::translate(to - rp) * scale, p, true)
}
fn reference_index(p: &Value) -> Result<usize> {
let reference = crate::cmd::number_or(p, "reference", 4.0, "object.setBounds")?;
if !reference.is_finite() || reference < 0.0 || reference.fract() != 0.0 {
return Err(crate::cmd::bad("object.setBounds", "`reference` must be a whole number"));
}
Ok(reference.min(8.0) as usize)
}
/// The visual box of `ids` square to `frame`, as [`Document::oriented_bounds`] measures it, with
/// symbol instances measured without the strokes in their art
/// ([`vectorcraft_doc::SymbolBoxes::without_art_strokes`]).
+10 -2
View File
@@ -245,7 +245,15 @@ pub fn specs() -> Vec<CommandSpec> {
crate::cmd::maskedit::outside_mask_editing,
isolate
),
cmd!("object.exitIsolation", "Exit Isolation Mode", [], None, "{}", has_doc, exit_isolation),
cmd!(
"object.exitIsolation",
"Exit Isolation Mode",
[],
None,
"{} leave isolation mode; leaving an isolated Live Paint group adds the paths, compound paths and groups of them drawn in it (shown and unlocked with everything in them) to the group as livePaint.merge does, in one undo step, and leaves type, images and other objects in it as they are; object.isolate on a level outside the group does the same",
has_doc,
exit_isolation
),
cmd!(
"object.setProps",
"Object Properties",
@@ -287,7 +295,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Set Bounds",
[],
None,
"{x?, y?, width?, height?, reference?: 0..8 (9-point grid; a number past 8 is read as 8), proportional?, strokes?, corners?, copy?: bool, patterns?: bool (Transform Patterns), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), objects?: bool (Transform Objects, as object.move)} (Transform panel; width/height and the reference point follow the bounding box, rotated with rotated objects; x, y are page coordinates; with Use Preview Bounds the values measure the visual bounds; with the typeGlyphBounds preference, each point type object selected as an object (not inside a selected group) is measured by its glyphs' ink (underline and strikethrough included), which the scale gives the size asked for; strokes/corners as object.scale; with anchor points selected (Direct Selection) and no copy, the values are the box around those points, square to the page, and only they move or scale, as with object.move (#1824))",
"{x?, y?, width?, height?, reference?: whole number >= 0 (9-point grid 0..8; 0.0 equals 0; a whole number past 8 is read as 8; omitted/null: center, 4), proportional?, strokes?, corners?, copy?: bool, patterns?: bool (Transform Patterns), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), objects?: bool (Transform Objects, as object.move)} (Transform panel; width/height and the reference point follow the bounding box, rotated with rotated objects; x, y are page coordinates; with Use Preview Bounds the values measure the visual bounds; with the typeGlyphBounds preference, each point type object selected as an object (not inside a selected group) is measured by its glyphs' ink (underline and strikethrough included), which the scale gives the size asked for; strokes/corners as object.scale; with anchor points selected (Direct Selection) and no copy, the values are the box around those points, square to the page, and only they move or scale, as with object.move (#1824))",
has_selection,
set_bounds
),
+11 -1
View File
@@ -1276,7 +1276,7 @@ fn aligned_between(tab: &vectorcraft_doc::TabStop, from: f64, x: f64) -> bool {
/// The frames of the story that type object `id` belongs to (its thread in thread order, else `id`
/// alone), each with the length of its text in bytes.
fn story_frames(s: &Session, id: NodeId) -> Vec<(NodeId, usize)> {
pub(crate) fn story_frames(s: &Session, id: NodeId) -> Vec<(NodeId, usize)> {
let Some(st) = s.active() else { return vec![] };
let d = &st.doc;
let frames = d.text_threads.iter().find(|thread| thread.contains(&id)).cloned().unwrap_or_else(|| vec![id]);
@@ -1314,6 +1314,16 @@ fn move_editing_selection(
at + inserted.iter().filter(|(b, _)| *b <= at).map(|(_, n)| n).sum::<usize>()
};
let (anchor, caret) = (story(anchor), story(caret));
select_story_range(s, id, anchor, caret)
}
/// The Type tool's anchor and caret become story positions `anchor` and `caret` of the story that
/// frame `id` belongs to, as its frames are now. The caret stays in `id` while its place is there,
/// and else goes to the frame that holds it, with the anchor in that frame; that frame becomes the
/// selection when it was not selected.
pub(crate) fn select_story_range(s: &mut Session, id: NodeId, anchor: usize, caret: usize) -> Result<()> {
let start_of = |frames: &[(NodeId, usize)], f: NodeId| frames.iter().take_while(|(g, _)| *g != f).map(|(_, n)| n).sum::<usize>();
let len_of = |frames: &[(NodeId, usize)], f: NodeId| frames.iter().find(|(g, _)| *g == f).map_or(0, |(_, n)| *n);
let after = story_frames(s, id);
let fits = |f: NodeId| (start_of(&after, f)..=start_of(&after, f) + len_of(&after, f)).contains(&caret);
let frame = if fits(id) { Some(id) } else { after.iter().map(|(f, _)| *f).find(|f| fits(*f)) };
+1 -1
View File
@@ -91,7 +91,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Placed File Info",
[],
None,
"{path | name | dataBase64 (a file's path, or its name with its bytes), page?, crop?, password?, thumbnail?: px, link?: bool, dxf?: {…}, layers?, hiddenLayers?, importSlices? (all as file.place)} what file.place would place, without placing it → {name, format, width, height (pt at 100%), pixelWidth?, pixelHeight?, ppi?: [x, y], colorMode?: RGB|Grayscale|CMYK (raster images), plates?: [ink names] (a DCS file), slices?: the user slices a PSD or PSB file would bring in, warnings, thumbnailBase64?: PNG of at most `thumbnail` (≤ 512) px on its longer side}",
"{path | name | dataBase64 (a file's path, or its name with its bytes), page?, crop?, password?, thumbnail?: px, link?: bool, dxf?: {…}, layers?, hiddenLayers?, importSlices? (all as file.place)} what file.place would place, without placing it → {name, format, width, height (pt at 100%), pixelWidth?, pixelHeight?, ppi?: [x, y], colorMode?: RGB|Grayscale|CMYK (raster images; opaque CMYK PSD/PSB merged images keep 8- or 16-bit inks within VectorCraft's 67,108,864-pixel native CMYK limit and allocation allowance; other CMYK composites use the RGB decoder's allocation limit), plates?: [ink names] (a DCS file), slices?: the user slices a PSD or PSB file would bring in, warnings, thumbnailBase64?: PNG of at most `thumbnail` (≤ 512) px on its longer side}",
always,
info
),
+5 -12
View File
@@ -1,6 +1,6 @@
//! Select menu.
use std::collections::BTreeSet;
use std::collections::{BTreeSet, HashSet};
use serde_json::{Value, json};
use vectorcraft_color::Paint;
@@ -466,7 +466,8 @@ fn reselect(s: &mut Session, _: &Value) -> Result<Value> {
fn inverse(s: &mut Session, _: &Value) -> Result<Value> {
let st = s.doc()?;
let ids: Vec<NodeId> = selectable(&st.doc, st.isolation).into_iter().filter(|id| !st.selection.contains(*id)).collect();
let selected: HashSet<NodeId> = st.selection.objects.iter().copied().collect();
let ids: Vec<NodeId> = selectable(&st.doc, st.isolation).into_iter().filter(|id| !selected.contains(id)).collect();
s.select(|_, sel| sel.set(ids.iter().copied()))?;
ok()
}
@@ -497,11 +498,7 @@ fn set(s: &mut Session, p: &Value) -> Result<Value> {
fn add(s: &mut Session, p: &Value) -> Result<Value> {
let ids = checked_ids_param(s, p, "ids", "select.add")?;
s.select(|_, sel| {
for i in ids {
sel.add(i);
}
})?;
s.select(|_, sel| sel.add_all(ids))?;
selection_result(s)
}
@@ -512,11 +509,7 @@ fn toggle(s: &mut Session, p: &Value) -> Result<Value> {
let value = p.get("id").ok_or_else(|| bad("select.toggle", "missing id or ids"))?;
vec![checked_id(s, value, "select.toggle")?]
};
s.select(|_, sel| {
for id in ids {
sel.toggle(id);
}
})?;
s.select(|_, sel| sel.toggle_all(ids))?;
selection_result(s)
}
+1 -1
View File
@@ -270,7 +270,7 @@ fn range_of(p: &Value, len: usize, cmd: &str) -> Result<(usize, usize)> {
Ok((a.min(b), a.max(b)))
}
fn edit_range(s: &mut Session, p: &Value) -> Result<Value> {
pub(crate) fn edit_range(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "text.editRange";
let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing `id`"))?;
let t = text_ref(s, id)?;
+52 -7
View File
@@ -10,8 +10,8 @@ use super::object::choice;
use super::threads::ThreadIndex;
use super::typecmd::{area_text, block_gaps, needed_room, refresh_bounds};
use super::{
CommandSpec, EngineError, Result, Session, bad, checked_ids_param, cmd, find_command, has_clipboard, has_doc, has_selection, number_or,
switch_or, targets, text_param,
CommandSpec, EngineError, Result, Session, bad, checked_ids_param, cmd, find_command, has_clipboard, has_doc, has_selection, named_ids,
number_or, switch_or, targets, text_param,
};
pub fn specs() -> Vec<CommandSpec> {
@@ -111,7 +111,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Insert Character",
["Type"],
None,
"{char: \"bullet\"|\"copyright\"|\"ellipsis\"|\"paragraph\"|\"registered\"|\"section\"|\"trademark\"|\"emDash\"|\"enDash\"|\"discretionaryHyphen\"|\"nonBreakingHyphen\"|\"doubleLeftQuote\"|\"doubleRightQuote\"|\"singleLeftQuote\"|\"singleRightQuote\"|\"emSpace\"|\"enSpace\"|\"hairSpace\"|\"sixthSpace\"|\"thinSpace\"|\"nonBreakingSpace\"|\"figureSpace\"|\"punctuationSpace\"|\"thirdSpace\"|\"quarterSpace\"|\"tab\"|\"forcedLineBreak\"|\"paragraphReturn\" | text: string | code: Windows Alt+0 code (0–255 in Windows-1252, a Unicode code point above: 176 → °, 151 → —) | unicode: hex code point (\"00B0\" or \"U+00B0\"), ids?|id?: object ids (default: the selection)} append to the selected text objects",
"{char: \"bullet\"|\"copyright\"|\"ellipsis\"|\"paragraph\"|\"registered\"|\"section\"|\"trademark\"|\"emDash\"|\"enDash\"|\"discretionaryHyphen\"|\"nonBreakingHyphen\"|\"doubleLeftQuote\"|\"doubleRightQuote\"|\"singleLeftQuote\"|\"singleRightQuote\"|\"emSpace\"|\"enSpace\"|\"hairSpace\"|\"sixthSpace\"|\"thinSpace\"|\"nonBreakingSpace\"|\"figureSpace\"|\"punctuationSpace\"|\"thirdSpace\"|\"quarterSpace\"|\"tab\"|\"forcedLineBreak\"|\"paragraphReturn\" | text: string | code: Windows Alt+0 code (0–255 in Windows-1252, a Unicode code point above: 176 → °, 151 → —) | unicode: hex code point (\"00B0\" or \"U+00B0\"), ids?|id?: object ids (default: the selection)} insert at the Type tool's caret, replacing its selection, while it edits text and no ids are given; otherwise append to the selected text objects. forcedLineBreak is U+2028, a new line in the same paragraph; paragraphReturn is a line feed, which starts a new paragraph",
has_selection,
insert_char
),
@@ -786,8 +786,9 @@ fn to_point(s: &mut Session, p: &Value) -> Result<Value> {
let plain = t.plain_text();
let baseline = lay.lines.first().map(|l| l.baseline).unwrap_or(fb.y0 + t.first_style().size * 0.8);
// Soft wraps → explicit breaks (replace the space before the wrap when there is one).
let mut breaks: Vec<usize> =
lay.lines.iter().skip(1).map(|l| l.start).filter(|&b| b > 0 && plain.as_bytes().get(b - 1) != Some(&b'\n')).collect();
// A line after a paragraph return or a forced line break (U+2028) already starts there.
let hard = |b: usize| plain.get(..b).is_some_and(|s| s.ends_with(['\n', '\u{2028}']));
let mut breaks: Vec<usize> = lay.lines.iter().skip(1).map(|l| l.start).filter(|&b| b > 0 && !hard(b)).collect();
breaks.sort_unstable();
breaks.dedup();
for b in breaks.into_iter().rev() {
@@ -1525,8 +1526,9 @@ pub(crate) fn special_char(name: &str) -> Option<&'static str> {
"thirdSpace" => "\u{2004}",
"quarterSpace" => "\u{2005}",
"tab" => "\t",
// Our text model breaks lines at paragraph returns only.
"forcedLineBreak" | "paragraphReturn" => "\n",
// A line break inside the paragraph, as Shift+Enter types it.
"forcedLineBreak" => "\u{2028}",
"paragraphReturn" => "\n",
_ => return None,
})
}
@@ -1576,6 +1578,11 @@ fn insert_char(s: &mut Session, p: &Value) -> Result<Value> {
(None, None, None, Some(u)) => unicode_char(u).ok_or_else(|| bad(C, format!("`{u}` is no Unicode character")))?.to_string(),
(None, None, None, None) => return Err(bad(C, "give `char`, `text`, `code` or `unicode`")),
};
if named_ids(p)?.is_none()
&& let Some(r) = insert_at_type_caret(s, &text)?
{
return Ok(r);
}
let ids = texts(s, p, C)?;
// When `text` is empty and every object ends with a run of text, the document and its undo
// history stay as they are.
@@ -1606,6 +1613,44 @@ fn insert_char(s: &mut Session, p: &Value) -> Result<Value> {
Ok(ids_json(&ids))
}
/// `type.insert` while the Type tool edits text: `text` replaces the tool's selection (inserts at
/// its caret) as one undo step, and the caret goes after it. `None` when no text is being edited.
fn insert_at_type_caret(s: &mut Session, text: &str) -> Result<Option<Value>> {
let tool = s.tool_options();
let Some(id) = tool.get("editing").and_then(Value::as_u64).map(NodeId) else { return Ok(None) };
let d = &s.doc()?.doc;
let Some(NodeKind::Text(t)) = d.node(id).map(|n| &n.kind) else { return Ok(None) };
let len = vectorcraft_text::edit::runs_len(&t.runs);
let g = |k: &str| tool.get(k).and_then(Value::as_u64).map_or(len, |v| (v as usize).min(len));
let (x, y) = (g("start"), g("end"));
let (a, b) = (x.min(y), x.max(y));
// After Select All in threaded text the whole story is selected: the other frames' text goes
// in the same edit, as when typing replaces it.
let story: Vec<NodeId> = tool.get("story").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_u64).map(NodeId).collect();
let clear: Vec<u64> = if a == 0 && b == len && story.contains(&id) {
let has_text = |f: &NodeId| matches!(d.node(*f).map(|n| &n.kind), Some(NodeKind::Text(o)) if !o.runs.iter().all(|r| r.text.is_empty()));
story.iter().filter(|f| **f != id && has_text(f)).map(|f| f.0).collect()
} else {
vec![]
};
if text.is_empty() && a == b && clear.is_empty() {
return Ok(Some(ids_json(&[id])));
}
// A typing session ends first: the insertion is a step of its own.
if tool.get("typing").and_then(Value::as_bool) == Some(true) {
s.set_tool_option("commitTyping", &Value::Bool(true));
s.commit_interaction()?;
}
// The frame's place in the story once the edit has cleared the frames in `clear`.
let start: usize =
super::panelcmds::story_frames(s, id).iter().take_while(|(f, _)| *f != id).filter(|(f, _)| !clear.contains(&f.0)).map(|(_, n)| n).sum();
let r = super::textedit::edit_range(s, &json!({"id": id.0, "start": a, "end": b, "insert": text, "clear": clear}))?;
let caret = r.get("caret").and_then(Value::as_u64).map_or(a + text.len(), |c| c as usize);
// Threaded text re-flows in the edit: the caret goes to the frame its place moved to.
super::panelcmds::select_story_range(s, id, start + caret, start + caret)?;
Ok(Some(ids_json(&[id])))
}
// ---------- Find and Replace ----------
fn is_word(c: char) -> bool {
+157
View File
@@ -246,6 +246,163 @@ fn export_3d_writes_into_a_folder_or_one_zip() {
let _ = std::fs::remove_dir_all(&dir);
}
/// A blue 100 × 100 square extruded straight on, with a red 10 × 20 graphic "Mark" mapped onto its
/// front at its center and onto its back 30 pt to the right (as the back is seen from behind),
/// collected as a 3D asset in `format`.
fn mapped(format: &str) -> (Session, u64) {
let mut s = session();
let mark = run(&mut s, "path.create", json!({"d": "M300 300L310 300L310 320L300 320Z"}))["id"].clone();
run(&mut s, "paint.setFill", json!({"color": "#ff0000"}));
run(&mut s, "threeD.addGraphic", json!({"name": "Mark", "ids": [mark]}));
let id = run(&mut s, "path.create", json!({"d": "M100 100L200 100L200 200L100 200Z"}))["id"].as_u64().unwrap();
run(&mut s, "paint.setFill", json!({"color": "#0000ff"}));
run(&mut s, "effect.apply", json!({"effect": "threeD.extrude", "params": {"rotationX": 0.0, "rotationY": 0.0, "rotationZ": 0.0, "depth": 20.0}}));
run(&mut s, "threeD.mapGraphic", json!({"symbol": "Mark", "ids": [id]}));
run(&mut s, "threeD.mapGraphic", json!({"symbol": "Mark", "face": "back", "x": 30.0, "ids": [id]}));
run(&mut s, "layer.setProps", json!({"id": id, "name": "Box"}));
let asset = run(&mut s, "assets.add3D", json!({"ids": [id], "format": format}))["assets"][0].as_u64().unwrap();
(s, asset)
}
/// The color of pixel `(x, y)` of PNG `png`.
fn pixel(png: &[u8], x: u32, y: u32) -> [u8; 4] {
image::load_from_memory(png).unwrap().to_rgba8().get_pixel(x, y).0
}
fn is_red(p: [u8; 4]) -> bool {
p[0] > 200 && p[1] < 50 && p[2] < 50 && p[3] == 255
}
fn is_blue(p: [u8; 4]) -> bool {
p[0] < 50 && p[1] < 50 && p[2] > 200 && p[3] == 255
}
#[test]
fn export_3d_paints_mapped_graphics_on_their_caps_in_every_format() {
for (format, names) in [
("usda", vec!["Box.usda", "Box-texture-1.png", "Box-texture-2.png"]),
("usdz", vec!["Box.usdz"]),
("gltf", vec!["Box.gltf"]),
("obj", vec!["Box.obj", "Box.mtl", "Box-texture-1.png", "Box-texture-2.png"]),
] {
let (mut s, _) = mapped(format);
let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128})));
assert_eq!(out.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), names, "{format}");
}
// The front's picture: the cap's 100 pt across 128 pixels, blue with the red graphic at the
// middle; the back's: the graphic 30 pt to the right as seen from behind, which is to the left
// in the art's plane.
let (mut s, _) = mapped("usda");
let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128})));
let (front, back) = (&out[1].1, &out[2].1);
assert_eq!(image::load_from_memory(front).unwrap().to_rgba8().dimensions(), (128, 128));
assert!(is_red(pixel(front, 64, 64)) && is_blue(pixel(front, 2, 2)) && is_blue(pixel(front, 64, 10)));
let at = |pt: f64| (pt * 1.28) as u32;
assert!(is_red(pixel(back, at(20.0), 64)) && is_blue(pixel(back, 64, 64)), "{:?}", pixel(back, 64, 64));
// The USDA's front cap shows the front picture through st, up from the picture's bottom.
let usda = String::from_utf8(out[0].1.clone()).unwrap();
assert_eq!(usda.matches("primvars:st").count(), 2);
assert_eq!(usda.matches("def Mesh").count(), 3, "the walls, the front cap and the back cap");
// glTF holds both pictures, and a cap's coordinates stay inside its picture.
let (mut s, _) = mapped("gltf");
let out = files(&run(&mut s, "assets.export3D", json!({})));
let g: Value = serde_json::from_slice(&out[0].1).unwrap();
assert_eq!(g["images"].as_array().map(Vec::len), Some(2));
let png = vectorcraft_format::base64_decode(g["images"][0]["uri"].as_str().unwrap().split(',').nth(1).unwrap()).unwrap();
assert_eq!(image::load_from_memory(&png).unwrap().to_rgba8().dimensions(), (1024, 1024), "1024 pixels by default");
}
#[test]
fn a_texture_takes_the_opacity_of_the_fill_and_of_the_object_as_the_canvas_draws_them() {
let half = |a: u8| (120..=135).contains(&a);
// A half-opaque fill: the face and the graphic over it are each drawn at half opacity, so the
// graphic covers three quarters.
let (mut s, asset) = mapped("usda");
let doc = &s.active().unwrap().doc;
let id = doc.asset(asset).unwrap().nodes[0];
let fill = doc.node(id).unwrap().appearance.items.iter().position(|i| matches!(i, vectorcraft_doc::AppearanceItem::Fill(_))).unwrap();
run(&mut s, "select.set", json!({"ids": [id.0]}));
run(&mut s, "transparency.set", json!({"item": fill, "opacity": 50}));
let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128})));
let (on, around) = (pixel(&out[1].1, 64, 64), pixel(&out[1].1, 2, 2));
assert!(on[0] > on[2] && (185..=197).contains(&on[3]), "{on:?}");
assert!(around[2] > 200 && half(around[3]), "{around:?}");
let usda = String::from_utf8(out[0].1.clone()).unwrap();
assert!(usda.contains("float inputs:opacity.connect"), "the texture's alpha is the opacity");
// An OBJ's opacity map has the alpha as gray levels.
run(&mut s, "assets.set3DFormat", json!({"assets": [asset], "format": "obj"}));
let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128})));
assert_eq!(out[3].0, "Box-texture-1-opacity.png");
let gray = image::load_from_memory(&out[3].1).unwrap().to_luma8();
let (g_on, g_around) = (gray.get_pixel(64, 64).0[0], gray.get_pixel(2, 2).0[0]);
assert!((185..=197).contains(&g_on) && half(g_around), "{g_on} {g_around}");
// A half-opaque object: the face and the graphic are drawn opaque, and the whole picture at
// half opacity.
let (mut s, asset) = mapped("usda");
let id = s.active().unwrap().doc.asset(asset).unwrap().nodes[0];
run(&mut s, "transparency.set", json!({"ids": [id.0], "opacity": 50}));
let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128})));
let (on, around) = (pixel(&out[1].1, 64, 64), pixel(&out[1].1, 2, 2));
assert!(on[0] > 200 && on[2] < 50 && half(on[3]), "{on:?}");
assert!(around[2] > 200 && around[0] < 50 && half(around[3]), "{around:?}");
// A gradient whose stops are clear: the face is clear, and the graphic keeps its opacity.
let (mut s, asset) = mapped("usda");
let id = s.active().unwrap().doc.asset(asset).unwrap().nodes[0];
run(&mut s, "select.set", json!({"ids": [id.0]}));
let clear = json!({"stops": [{"offset": 0, "color": "#0000ff", "opacity": 0}, {"offset": 1, "color": "#0000ff", "opacity": 0}]});
run(&mut s, "paint.setFill", json!({"gradient": clear}));
let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128})));
let (on, around) = (pixel(&out[1].1, 64, 64), pixel(&out[1].1, 2, 2));
assert!(is_red(on), "{on:?}");
assert_eq!(around[3], 0, "{around:?}");
}
#[test]
fn export_3d_keeps_flat_colors_without_graphics_and_refuses_bad_texture_sizes() {
let (mut s, asset) = mapped("obj");
for bad in [json!(64), json!(5000), json!(512.5), json!("512"), json!(-1)] {
assert!(s.execute("assets.export3D", &json!({"textureSize": bad})).is_err(), "{bad}");
}
// Without its graphics the box is one plain mesh, as before.
let id = s.doc().unwrap().doc.asset(asset).unwrap().nodes[0].0;
run(&mut s, "select.set", json!({"ids": [id]}));
run(&mut s, "effect.setParams", json!({"index": 0, "params": {"graphics": []}}));
let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128})));
assert_eq!(out.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), ["Box.obj", "Box.mtl"]);
let obj = String::from_utf8(out[0].1.clone()).unwrap();
assert!(!obj.contains("vt ") && obj.lines().filter(|l| l.starts_with("g ")).count() == 1);
}
#[test]
fn texture_pixels_are_counted_across_one_export() {
let (s, asset) = mapped("gltf");
let d = &s.doc().unwrap().doc;
let node = d.node(d.asset(asset).unwrap().nodes[0]).unwrap();
let parts = vectorcraft_render::effects::three_d_meshes_in(Some(d), node).unwrap();
let mut pixels = 0;
let made = crate::cmd::fileio::textures(d, &parts, 128, &mut pixels).unwrap();
assert_eq!((made.iter().flatten().count(), pixels), (2, 2 * 128 * 128));
let mut pixels = crate::cmd::fileio::MAX_TEXTURE_PIXELS - 128 * 128;
let e = crate::cmd::fileio::textures(d, &parts, 128, &mut pixels).unwrap_err();
assert!(e.contains("textureSize"), "{e}");
}
#[test]
fn only_graphics_that_draw_count_as_textures() {
let parts_of = |s: &Session, asset: u64| {
let d = &s.doc().unwrap().doc;
let node = d.node(d.asset(asset).unwrap().nodes[0]).unwrap();
vectorcraft_render::effects::three_d_meshes_in(Some(d), node).unwrap()
};
let (mut s, asset) = mapped("obj");
assert!(crate::cmd::fileio::draws_textures(&s.doc().unwrap().doc, &parts_of(&s, asset)));
// With its symbol gone the graphic draws nothing, so the export writes no texture.
run(&mut s, "symbol.delete", json!({"name": "Mark"}));
assert!(!crate::cmd::fileio::draws_textures(&s.doc().unwrap().doc, &parts_of(&s, asset)));
let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128})));
assert_eq!(out.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), ["Box.obj", "Box.mtl"]);
}
#[test]
fn three_d_assets_round_trip_through_the_native_format() {
let mut s = session();
+69
View File
@@ -428,6 +428,75 @@ fn transform_panel_sizes_follow_the_turned_box() {
assert!(near(angle(&s, a), 45.0));
}
#[test]
fn set_bounds_whole_number_references_match_integer_references() {
for direct in [false, true] {
for index in 0..=9 {
let run = |reference: Value| {
let mut s = session();
let a = rect(&mut s, 10.0, 20.0, 100.0, 50.0);
sel(&mut s, &[a]);
if direct {
s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 0], [0, 2]], "mode": "set"})).unwrap();
}
let before = anchors(&s, a);
let selection = s.doc().unwrap().selection.clone();
let n = undo_len(&s);
s.execute("object.setBounds", &json!({"x": 200, "y": 300, "reference": reference})).unwrap();
assert_eq!(undo_len(&s), n + 1);
assert_eq!(s.doc().unwrap().selection, selection);
if !direct {
let b = selection_box(&s);
assert!(b.reference_point(index.min(8)).distance(Point::new(200.0, 300.0)) < 1e-6, "{b:?}");
}
let after = anchors(&s, a);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(anchors(&s, a), before);
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(anchors(&s, a), after);
after
};
assert_eq!(run(json!(index as f64)), run(json!(index)), "reference {index}, direct {direct}");
if index == 8 {
assert_eq!(run(json!(u64::MAX)), run(json!(8)), "large reference, direct {direct}");
assert_eq!(run(json!(1e100)), run(json!(8)), "large float reference, direct {direct}");
}
}
}
for reference in [None, Some(Value::Null)] {
let mut s = session();
let a = rect(&mut s, 10.0, 20.0, 100.0, 50.0);
sel(&mut s, &[a]);
let mut p = json!({"x": 200, "y": 300});
if let Some(reference) = reference {
p["reference"] = reference;
}
s.execute("object.setBounds", &p).unwrap();
assert!(selection_box(&s).center().distance(Point::new(200.0, 300.0)) < 1e-6);
}
}
#[test]
fn set_bounds_rejects_invalid_references_without_changes() {
for direct in [false, true] {
for reference in [json!(-1), json!(-1.0), json!(0.5), json!(8.5), json!("0"), json!(true), json!([]), json!({})] {
let mut s = session();
let a = rect(&mut s, 10.0, 20.0, 100.0, 50.0);
sel(&mut s, &[a]);
if direct {
s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 0], [0, 2]], "mode": "set"})).unwrap();
}
let before = anchors(&s, a);
let selection = s.doc().unwrap().selection.clone();
let n = undo_len(&s);
assert!(s.execute("object.setBounds", &json!({"x": 200, "y": 300, "reference": reference})).is_err(), "{reference}, direct {direct}");
assert_eq!(anchors(&s, a), before);
assert_eq!(s.doc().unwrap().selection, selection);
assert_eq!(undo_len(&s), n);
}
}
}
#[test]
fn reset_bounding_box_squares_the_box_in_one_step() {
let mut s = session();
+273
View File
@@ -4762,6 +4762,279 @@ fn live_paint_refuses_type_and_images_and_changes_nothing() {
assert!(!vectorcraft_tools::builder::live_paint_takes(&node(&s, text_group)));
}
/// A horizontal open path across [`live`]'s group at `y`, drawn with the Pen's defaults.
fn line_across(s: &mut Session, y: f64) -> NodeId {
let r = s.execute("path.create", &json!({"anchors": [{"x": -10, "y": y}, {"x": 160, "y": y}]})).unwrap();
NodeId(r["id"].as_u64().unwrap())
}
/// Paths drawn in an isolated Live Paint group join it when isolation mode ends: they go among its
/// sources and cut the faces they cross, which take their sources' fill, a painted face they do not
/// cross keeps its fill, and the whole addition is one undo step, which Undo takes back to the
/// drawn paths in the group and Redo makes again.
#[test]
fn live_paint_isolation_adds_drawn_paths_on_exit() {
use vectorcraft_tools::builder::{face_at, faces, sources};
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
let mut s = session();
let g = live(&mut s);
s.execute("livePaint.fill", &json!({"group": g.0, "point": [125, 50], "color": "#00ff00"})).unwrap();
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
// Two lines from left of the group that end in its right face, so they cut only the other two.
let line = |s: &mut Session, y: f64| {
let r = s.execute("path.create", &json!({"anchors": [{"x": -10, "y": y}, {"x": 105, "y": y}]})).unwrap();
NodeId(r["id"].as_u64().unwrap())
};
let (a, b) = (line(&mut s, 30.0), line(&mut s, 70.0));
assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(g), "a path drawn in isolation goes into the group");
let steps = s.doc().unwrap().history.undo.len();
s.execute("object.exitIsolation", &json!({})).unwrap();
let d = s.doc().unwrap();
assert_eq!(d.isolation, None);
assert_eq!(d.history.undo.len(), steps + 1, "both paths join in one undo step");
assert_eq!(d.selection.objects, vec![g]);
let n = node(&s, g);
let src = sources(&n).unwrap();
assert_eq!(src.children().unwrap().len(), 4);
for id in [a, b] {
assert_eq!(s.doc().unwrap().doc.parent_of(id), Some(src.id), "{id} joined the sources");
}
assert_eq!(faces(&n).len(), 7, "two lines cut each of the two faces they cross in three");
assert_eq!(face_at(&n, Point::new(125.0, 50.0)).unwrap().appearance.fill_paint(), green, "the face the lines do not cross keeps its fill");
let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0));
for y in [15.0, 85.0] {
assert_eq!(face_at(&n, Point::new(25.0, y)).unwrap().appearance.fill_paint(), red, "a new face takes its source's fill");
}
s.execute("edit.undo", &json!({})).unwrap();
let n = node(&s, g);
assert_eq!(faces(&n).len(), 3);
assert_eq!(sources(&n).unwrap().children().unwrap().len(), 2);
for id in [a, b] {
assert_eq!(s.doc().unwrap().doc.parent_of(id), Some(g), "Undo puts {id} back in the group as drawn");
}
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(faces(&node(&s, g)).len(), 7);
}
/// Leaving isolation mode in a Live Paint group with nothing drawn in it records no undo step and
/// leaves the document as it is. Type, and a path that is hidden, stay in the group as they are,
/// while a group of paths drawn beside them joins it.
#[test]
fn live_paint_isolation_adds_only_paths_it_takes() {
use vectorcraft_tools::builder::{faces, sources};
let mut s = session();
let g = live(&mut s);
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
let before = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len());
s.execute("object.exitIsolation", &json!({})).unwrap();
assert!(s.doc().unwrap().doc == before.0, "an exit with nothing drawn changes nothing");
assert_eq!(s.doc().unwrap().history.undo.len(), before.1, "and records no undo step");
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
let text = NodeId(s.execute("text.create", &json!({"x": 20, "y": 20, "text": "Hi"})).unwrap()["id"].as_u64().unwrap());
let hidden = line_across(&mut s, 50.0);
s.edit("t", |d, _| {
d.node_mut(hidden).unwrap().visible = false;
Ok(())
})
.unwrap();
let steps = s.doc().unwrap().history.undo.len();
s.execute("object.exitIsolation", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().history.undo.len(), steps, "type and a hidden path add nothing");
assert_eq!(faces(&node(&s, g)).len(), 3);
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
let (a, b) = (line_across(&mut s, 30.0), line_across(&mut s, 70.0));
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
let paths = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
assert_eq!(s.doc().unwrap().doc.parent_of(paths), Some(g));
s.execute("object.exitIsolation", &json!({})).unwrap();
let n = node(&s, g);
assert_eq!(faces(&n).len(), 9, "the group of paths joined");
let d = &s.doc().unwrap().doc;
assert_eq!(d.parent_of(paths), Some(sources(&n).unwrap().id));
for id in [text, hidden] {
assert_eq!(d.parent_of(id), Some(g), "{id} stays in the group");
assert!(d.node(id).is_some());
}
}
/// A group drawn in an isolated Live Paint group that holds a locked path stays in it as it is when
/// isolation mode ends, as a locked path drawn there does.
#[test]
fn live_paint_isolation_leaves_a_group_holding_a_locked_path() {
use vectorcraft_tools::builder::faces;
let mut s = session();
let g = live(&mut s);
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
let (a, b) = (line_across(&mut s, 30.0), line_across(&mut s, 70.0));
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
let paths = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
s.edit("t", |d, _| {
d.node_mut(b).unwrap().locked = true;
Ok(())
})
.unwrap();
let steps = s.doc().unwrap().history.undo.len();
s.execute("object.exitIsolation", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().history.undo.len(), steps);
assert_eq!(s.doc().unwrap().doc.parent_of(paths), Some(g));
assert_eq!(faces(&node(&s, g)).len(), 3);
}
/// Type drawn in an isolated Live Paint group stays in it when Gap Options or Merge make the group's
/// faces and edges again, including type in a Live Paint group merged into another, and Release
/// puts it beside the released paths.
#[test]
fn live_paint_keeps_type_drawn_in_it_through_gap_options_merge_and_release() {
let mut s = session();
let g = live(&mut s);
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
let text = NodeId(s.execute("text.create", &json!({"x": 20, "y": 20, "text": "Hi"})).unwrap()["id"].as_u64().unwrap());
s.execute("object.exitIsolation", &json!({})).unwrap();
s.execute("livePaint.gapOptions", &json!({"ids": [g.0], "detect": true})).unwrap();
assert_eq!(s.doc().unwrap().doc.parent_of(text), Some(g), "Gap Options keeps the type");
let c = rect(&mut s, 120.0, 20.0, 100.0, 20.0);
s.execute("livePaint.merge", &json!({"ids": [g.0, c.0]})).unwrap();
assert_eq!(s.doc().unwrap().doc.parent_of(text), Some(g), "Merge keeps the type");
let other = rect(&mut s, 300.0, 300.0, 50.0, 50.0);
let h = NodeId(s.execute("livePaint.make", &json!({"ids": [other.0]})).unwrap()["id"].as_u64().unwrap());
s.execute("object.isolate", &json!({"id": h.0})).unwrap();
let text2 = NodeId(s.execute("text.create", &json!({"x": 310, "y": 320, "text": "Yo"})).unwrap()["id"].as_u64().unwrap());
s.execute("object.exitIsolation", &json!({})).unwrap();
s.execute("livePaint.merge", &json!({"ids": [g.0, h.0]})).unwrap();
assert_eq!(s.doc().unwrap().doc.parent_of(text2), Some(g), "the type of the merged group moves with its paths");
s.execute("livePaint.release", &json!({"ids": [g.0]})).unwrap();
let d = &s.doc().unwrap().doc;
for id in [text, text2] {
assert_eq!(d.parent_of(id), d.default_layer(), "Release keeps {id}");
}
}
/// Art drawn in an isolated Live Paint group and named like one of the group's parts is not taken
/// for one: type named "Live Paint Sources" stays in the group through Gap Options, and a group of
/// paths named "Face" joins the group when isolation mode ends.
#[test]
fn live_paint_isolation_keeps_art_named_like_its_parts() {
use vectorcraft_tools::builder::{SOURCES_NAME, faces, sources};
let mut s = session();
let g = live(&mut s);
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
let text = NodeId(s.execute("text.create", &json!({"x": 20, "y": 20, "text": "Hi"})).unwrap()["id"].as_u64().unwrap());
s.execute("object.setProps", &json!({"id": text.0, "name": SOURCES_NAME})).unwrap();
let (a, b) = (line_across(&mut s, 30.0), line_across(&mut s, 70.0));
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
let paths = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
s.execute("object.setProps", &json!({"id": paths.0, "name": "Face"})).unwrap();
s.execute("object.exitIsolation", &json!({})).unwrap();
let n = node(&s, g);
assert_eq!(faces(&n).len(), 9, "the group named Face joined");
assert_eq!(s.doc().unwrap().doc.parent_of(paths), Some(sources(&n).unwrap().id));
s.execute("livePaint.gapOptions", &json!({"ids": [g.0], "detect": true})).unwrap();
assert_eq!(s.doc().unwrap().doc.parent_of(text), Some(g), "Gap Options keeps the type named like the sources");
}
/// Type drawn in an isolated Live Paint group under the name of a face, an edge or the sources
/// group is not one of the group's parts: Gap Options, Info and Make count only the faces and edges
/// Live Paint made, and Expand keeps the type.
#[test]
fn live_paint_does_not_count_art_named_like_its_parts() {
use vectorcraft_tools::builder::{EDGE_NAME, FACE_NAME, SOURCES_NAME};
let mut s = session();
let g = live(&mut s);
let edges = s.execute("livePaint.info", &json!({"group": g.0})).unwrap()["edges"].as_array().unwrap().len();
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
let mut texts = vec![];
for (i, name) in [FACE_NAME, EDGE_NAME, SOURCES_NAME].into_iter().enumerate() {
let r = s.execute("text.create", &json!({"x": 20 + 20 * i, "y": 20, "text": "Hi"})).unwrap();
let t = NodeId(r["id"].as_u64().unwrap());
s.execute("object.setProps", &json!({"id": t.0, "name": name})).unwrap();
texts.push(t);
}
s.execute("object.exitIsolation", &json!({})).unwrap();
let r = s.execute("livePaint.gapOptions", &json!({"ids": [g.0], "detect": true})).unwrap();
assert_eq!(r["faces"], 3, "Gap Options counts the faces Live Paint made");
let info = s.execute("livePaint.info", &json!({"group": g.0})).unwrap();
assert_eq!(info["faces"].as_array().unwrap().len(), 3);
assert_eq!(info["edges"].as_array().unwrap().len(), edges);
let r = s.execute("livePaint.make", &json!({"ids": [g.0]})).unwrap();
assert_eq!((r["faces"].as_u64(), r["edges"].as_u64()), (Some(3), Some(edges as u64)));
s.execute("livePaint.expand", &json!({"ids": [g.0]})).unwrap();
let d = &s.doc().unwrap().doc;
for t in texts {
assert_eq!(d.parent_of(t), Some(g), "Expand keeps {t}");
}
}
/// With Real-time Drawing and Editing off, a rectangle still being drawn in a Live Paint group
/// isolated in a pattern tile is drawn first when Exit Isolation Mode leaves pattern editing, and
/// joins the group with the tile saved.
#[test]
fn live_paint_in_a_pattern_tile_adds_a_shape_still_being_drawn_on_exit() {
use vectorcraft_tools::builder::{is_live_paint, sources};
let mut s = session();
two(&mut s);
s.execute("object.pattern.make", &json!({"name": "P"})).unwrap();
let g = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap());
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
s.execute("prefs.set", &json!({"key": "realTimeDrawing", "value": false})).unwrap();
let v = ViewInfo::default();
s.select_tool("rectangle", v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Down, 10.0, 10.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 40.0, 40.0), v).unwrap();
assert!(s.interaction_unapplied());
s.execute("object.exitIsolation", &json!({})).unwrap();
let st = s.doc().unwrap();
assert!(st.doc.pattern_edit.is_none());
let art = &st.doc.pattern("P").unwrap().art;
let n = art.iter().find(|n| is_live_paint(n)).expect("the tile holds the Live Paint group");
assert_eq!(sources(n).unwrap().children().unwrap().len(), 3, "the rectangle joined the sources");
}
/// Isolating a level outside an isolated Live Paint group, as the isolation bar's back arrow does,
/// leaves the group and adds the paths drawn in it; isolating a path drawn in it does not.
#[test]
fn live_paint_isolation_adds_drawn_paths_when_isolating_a_level_outside() {
use vectorcraft_tools::builder::{faces, sources};
let mut s = session();
let g = live(&mut s);
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
let a = line_across(&mut s, 50.0);
s.execute("object.isolate", &json!({"id": a.0})).unwrap();
assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(g), "the path is still being drawn in the group");
assert_eq!(faces(&node(&s, g)).len(), 3);
let layer = s.doc().unwrap().doc.parent_of(g).unwrap();
s.execute("object.isolate", &json!({"id": layer.0})).unwrap();
assert_eq!(s.doc().unwrap().isolation, Some(layer));
let n = node(&s, g);
assert_eq!(faces(&n).len(), 6);
assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(sources(&n).unwrap().id));
}
/// A group of paths drawn in an isolated Live Paint group and then isolated itself joins the Live
/// Paint group when isolation mode ends, or when a level outside the Live Paint group is isolated.
#[test]
fn live_paint_isolation_adds_a_drawn_group_isolated_inside_it() {
use vectorcraft_tools::builder::{faces, sources};
for to_layer in [false, true] {
let mut s = session();
let g = live(&mut s);
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
let (a, b) = (line_across(&mut s, 30.0), line_across(&mut s, 70.0));
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
let paths = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
s.execute("object.isolate", &json!({"id": paths.0})).unwrap();
assert_eq!(faces(&node(&s, g)).len(), 3, "isolating the drawn group stays in the Live Paint group");
if to_layer {
let layer = s.doc().unwrap().doc.parent_of(g).unwrap();
s.execute("object.isolate", &json!({"id": layer.0})).unwrap();
} else {
s.execute("object.exitIsolation", &json!({})).unwrap();
}
let n = node(&s, g);
assert_eq!(faces(&n).len(), 9, "the drawn group joined (to the layer: {to_layer})");
assert_eq!(s.doc().unwrap().doc.parent_of(paths), Some(sources(&n).unwrap().id));
}
}
/// Give Live Paint group `g` a lock, hidden state, appearance, knockout, opacity mask and
/// graphic style link, and return it as it then is.
fn dress_live_group(s: &mut Session, g: NodeId) -> Node {
+89
View File
@@ -506,3 +506,92 @@ fn arc_rotation_turns_it_and_must_be_a_number() {
}
}
}
/// The outer end of the spiral `id`.
fn spiral_outer_end(s: &Session, id: NodeId) -> Point {
*path_points(s, id).last().unwrap()
}
/// A spiral dragged out turns about its center so that its outer end is at the pointer, in every
/// direction and with a turned Constrain Angle too; its bounding box stays on the page, except
/// along the turned x axis, where it is the click dialog's spiral with its turned box.
#[test]
fn a_dragged_spiral_turns_its_outer_end_to_the_pointer() {
let mut s = new_doc();
for deg in [0.0, 30.0] {
set_angle(&mut s, deg);
s.select_tool("spiral", ViewInfo::default()).unwrap();
for (x, y) in [(260.0, 200.0), (200.0, 260.0), (140.0, 200.0), (200.0, 140.0), (240.0, 170.0)] {
gesture(&mut s, Mods::default(), &[(Down, 200.0, 200.0), (Drag, 230.0, 230.0), (Drag, x, y), (Up, x, y)]);
let id = last_id(&s);
let end = spiral_outer_end(&s, id);
assert!(near(end, x, y), "{deg}°, to ({x}, {y}): {end:?}");
assert_eq!(bbox_angle(&s, id).to_bits(), 0.0f64.to_bits(), "{deg}°, to ({x}, {y})");
}
}
let mut s = new_doc();
set_angle(&mut s, 90.0);
s.select_tool("spiral", ViewInfo::default()).unwrap();
gesture(&mut s, Mods::default(), &[(Down, 200.0, 200.0), (Drag, 230.0, 230.0), (Drag, 200.0, 150.0), (Up, 200.0, 150.0)]);
let id = last_id(&s);
assert_eq!(spiral_outer_end(&s, id), Point::new(200.0, 150.0));
assert_eq!(bbox_angle(&s, id), 90.0, "along the turned x axis");
}
/// A spiral placed by the click dialog starts along the turned x axis, about the click: at 90° its
/// outer end is straight above the center, exactly, and its bounding box turns with it; at 0°, a
/// whole turn and with a `rotation` given the dialog's params are unchanged.
#[test]
fn constrain_angle_turns_a_click_made_spiral() {
let mut s = new_doc();
let click = Point::new(200.0, 200.0);
let p = json!({"cx": 200.0, "cy": 200.0, "radius": 50.0, "decay": 80.0, "segments": 10, "clockwise": true});
assert_eq!(constrain_click(&s, "shape.spiral", p.clone(), click), p, "0°");
set_angle(&mut s, 360.0);
assert_eq!(constrain_click(&s, "shape.spiral", p.clone(), click), p, "a whole turn");
set_angle(&mut s, 90.0);
let mut given = p.clone();
given["rotation"] = json!(10.0);
assert_eq!(constrain_click(&s, "shape.spiral", given.clone(), click), given, "a given rotation");
let turned = constrain_click(&s, "shape.spiral", p.clone(), click);
assert_eq!(turned["rotation"], json!(-90.0));
let id = NodeId(s.execute("shape.spiral", &turned).unwrap()["id"].as_u64().unwrap());
assert_eq!(spiral_outer_end(&s, id), Point::new(200.0, 150.0));
assert_eq!(bbox_angle(&s, id), 90.0);
set_angle(&mut s, 30.0);
let id = NodeId(s.execute("shape.spiral", &constrain_click(&s, "shape.spiral", p, click)).unwrap()["id"].as_u64().unwrap());
let r = 30f64.to_radians();
let end = spiral_outer_end(&s, id);
assert!(near(end, 200.0 + 50.0 * r.cos(), 200.0 - 50.0 * r.sin()), "{end:?}");
assert!(close(bbox_angle(&s, id), 30.0), "{}", bbox_angle(&s, id));
}
/// `shape.spiral` turns by an explicit `rotation` (clockwise) about its center; 0 and a whole
/// turn draw it exactly as without one; a `rotation` that is not a number is refused and adds
/// nothing.
#[test]
fn spiral_rotation_turns_it_and_must_be_a_number() {
let mut s = new_doc();
let base = json!({"cx": 100, "cy": 100, "radius": 40, "segments": 6});
let with = |r: Value| {
let mut p = base.clone();
p["rotation"] = r;
p
};
let plain = NodeId(s.execute("shape.spiral", &base).unwrap()["id"].as_u64().unwrap());
let plain = path_points(&s, plain);
assert_eq!(*plain.last().unwrap(), Point::new(140.0, 100.0), "upright: the outer end to the right");
for r in [json!(0), json!(360)] {
let id = NodeId(s.execute("shape.spiral", &with(r.clone())).unwrap()["id"].as_u64().unwrap());
assert_eq!(path_points(&s, id), plain, "{r}");
assert_eq!(bbox_angle(&s, id).to_bits(), 0.0f64.to_bits(), "{r}");
}
let id = NodeId(s.execute("shape.spiral", &with(json!(90))).unwrap()["id"].as_u64().unwrap());
assert_eq!(spiral_outer_end(&s, id), Point::new(100.0, 140.0), "a quarter turn clockwise");
assert_eq!(bbox_angle(&s, id).to_bits(), 0.0f64.to_bits(), "not the Constrain Angle's turn");
for bad in [json!("x"), Value::Null, json!(true)] {
let p = with(bad);
assert!(s.execute("shape.spiral", &p).is_err(), "{p}");
assert_eq!(last_id(&s), id, "nothing added for {p}");
}
}
+135
View File
@@ -615,6 +615,141 @@ fn clicking_an_image_samples_its_pixel() {
assert_eq!(node(&s, dst).appearance.fill_paint().color(), Some(Color::rgb8(128, 128, 64)), "5 x 5 average of both pixels");
}
/// Gradient mesh points picked with Direct Selection or the Mesh tool take the color the
/// Eyedropper then samples from an image or from other art, each sample one undo step, and only
/// they change: the mesh's other points and its appearance stay as they were (#8090).
#[test]
fn picked_mesh_points_take_the_eyedropper_sample() {
let mut s = session();
// Two pixels, orange and teal, 100 pt each, at (300, 0).
let rgba = [[255u8, 128, 0, 255], [0, 128, 128, 255]].concat();
let img = craft_image_codecs::Image::from_raw(2, 1, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, rgba).unwrap();
let png = craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap();
s.edit("Place", |d, _| {
d.images.insert("px".into(), ImageBlob::png(png.to_vec()));
let l = d.layers[0].id;
let id = d.alloc_id();
let xf = vectorcraft_geom::Affine::translate((300.0, 0.0)) * vectorcraft_geom::Affine::scale(100.0);
let im = ImageObject { key: "px".into(), width: 2, height: 1, xf, link: None, placement: Default::default(), pixels: None };
d.insert(Some(l), 0, Node::new(id, NodeKind::Image(Box::new(im)))).map_err(|e| crate::EngineError::Other(e.to_string()))
})
.unwrap();
let m = rect(&mut s, 10.0);
s.execute("object.mesh.create", &json!({"ids": [m.0], "rows": 1, "cols": 1})).unwrap();
let red = rect(&mut s, 100.0);
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
let colors = |s: &Session| match node(s, m).kind {
NodeKind::Mesh(g) => g.points.iter().map(|p| p.color).collect::<Vec<_>>(),
k => panic!("not a mesh: {k:?}"),
};
let white = colors(&s)[0];
assert!(colors(&s).iter().all(|c| *c == white && *c != Color::rgb8(255, 0, 0)));
let appearance = node(&s, m).appearance;
let v = ViewInfo::default();
let pick = |s: &mut Session, tool: &str, i: usize, shift: bool| {
s.select_tool(tool, v).unwrap();
let q = match node(s, m).kind {
NodeKind::Mesh(g) => g.points[i].p,
k => panic!("not a mesh: {k:?}"),
};
let mods = Mods { shift, ..Default::default() };
for kind in [PointerKind::Down, PointerKind::Up] {
s.pointer(&PointerEvent::new(kind, q.x, q.y).with_mods(mods), v).unwrap();
}
};
let (teal, orange) = (Color::rgb8(0, 128, 128), Color::rgb8(255, 128, 0));
s.execute("select.set", &json!({"ids": [m.0]})).unwrap();
pick(&mut s, "directSelection", 0, false);
let undo = undo_len(&s);
click(&mut s, 450.0, 50.0, Mods::default());
assert_eq!(colors(&s), [teal, white, white, white], "the picked point takes the image's color");
assert_eq!(node(&s, m).appearance, appearance, "the mesh's appearance stays");
assert_eq!(undo_len(&s), undo + 1, "one undo step");
// The Eyedropper keeps the picks: a Shift-click samples into the point again.
s.pointer(&PointerEvent::new(PointerKind::Down, 350.0, 50.0).with_mods(Mods { shift: true, ..Default::default() }), v).unwrap();
assert_eq!(colors(&s), [orange, white, white, white]);
assert_eq!(undo_len(&s), undo + 2);
// A sample of the color the point already has changes nothing and adds no step.
s.pointer(&PointerEvent::new(PointerKind::Down, 350.0, 50.0), v).unwrap();
assert_eq!(undo_len(&s), undo + 2, "no step when nothing changes");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(colors(&s), [teal, white, white, white]);
// Two points picked with the Mesh tool both take a plain click's sample of other art, and the
// art keeps its fill.
pick(&mut s, "mesh", 1, false);
pick(&mut s, "mesh", 3, true);
let undo = undo_len(&s);
click(&mut s, 125.0, 35.0, Mods::default());
let r = Color::rgb8(255, 0, 0);
assert_eq!(colors(&s), [teal, r, white, r]);
assert_eq!(undo_len(&s), undo + 1, "one undo step for every picked point");
assert_eq!(node(&s, m).appearance, appearance);
assert_eq!(node(&s, red).appearance.fill_paint().color(), Some(r));
// Back in the Mesh tool the two points are still picked: a fill color recolors just them.
s.select_tool("mesh", v).unwrap();
s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap();
let b = Color::rgb8(0, 0, 255);
assert_eq!(colors(&s), [teal, b, white, b], "the picks go back to the Mesh tool");
// Without picked points a click on an image samples into the whole selected mesh as before.
s.select_tool("selection", v).unwrap();
s.execute("select.set", &json!({"ids": [m.0]})).unwrap();
click(&mut s, 450.0, 50.0, Mods::default());
assert_eq!(colors(&s), [teal, b, white, b], "the points keep their colors");
assert_ne!(node(&s, m).appearance, appearance);
}
/// A Cmd-click with the Direct Selection tool the Eyedropper lends picks gradient mesh points for
/// the Eyedropper: the lent tool starts from the Eyedropper's picks, so a Shift-click adds to
/// them, and the Eyedropper samples into what the lent tool left picked (#8090).
#[test]
fn mesh_points_picked_through_the_lent_tool_take_the_eyedropper_sample() {
let mut s = session();
// Two pixels, orange and teal, 100 pt each, at (300, 0).
let rgba = [[255u8, 128, 0, 255], [0, 128, 128, 255]].concat();
let img = craft_image_codecs::Image::from_raw(2, 1, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, rgba).unwrap();
let png = craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap();
s.edit("Place", |d, _| {
d.images.insert("px".into(), ImageBlob::png(png.to_vec()));
let l = d.layers[0].id;
let id = d.alloc_id();
let xf = vectorcraft_geom::Affine::translate((300.0, 0.0)) * vectorcraft_geom::Affine::scale(100.0);
let im = ImageObject { key: "px".into(), width: 2, height: 1, xf, link: None, placement: Default::default(), pixels: None };
d.insert(Some(l), 0, Node::new(id, NodeKind::Image(Box::new(im)))).map_err(|e| crate::EngineError::Other(e.to_string()))
})
.unwrap();
let m = rect(&mut s, 10.0);
s.execute("object.mesh.create", &json!({"ids": [m.0], "rows": 1, "cols": 1})).unwrap();
let colors = |s: &Session| match node(s, m).kind {
NodeKind::Mesh(g) => g.points.iter().map(|p| p.color).collect::<Vec<_>>(),
k => panic!("not a mesh: {k:?}"),
};
let white = colors(&s)[0];
let v = ViewInfo::default();
let press = |s: &mut Session, i: usize, mods: Mods| {
let q = match node(s, m).kind {
NodeKind::Mesh(g) => g.points[i].p,
k => panic!("not a mesh: {k:?}"),
};
for kind in [PointerKind::Down, PointerKind::Up] {
s.pointer(&PointerEvent::new(kind, q.x, q.y).with_mods(mods), v).unwrap();
}
};
let (teal, orange) = (Color::rgb8(0, 128, 128), Color::rgb8(255, 128, 0));
s.execute("select.set", &json!({"ids": [m.0]})).unwrap();
s.select_tool("directSelection", v).unwrap();
press(&mut s, 0, Mods::default());
s.select_tool("eyedropper", v).unwrap();
// Cmd-click point 3: Direct Selection, lent, picks it in place of point 0.
press(&mut s, 3, Mods { cmd: true, ..Default::default() });
assert_eq!(s.tool_id(), "eyedropper");
click(&mut s, 450.0, 50.0, Mods::default());
assert_eq!(colors(&s), [white, white, white, teal], "the point the lent tool picked takes the sample");
// Cmd+Shift-click point 0 adds it to the Eyedropper's pick.
press(&mut s, 0, Mods { cmd: true, shift: true, ..Default::default() });
click(&mut s, 350.0, 50.0, Mods::default());
assert_eq!(colors(&s), [orange, white, white, orange], "both picked points take the sample");
}
/// A CMYK document with one image of `px` (one row, 100 pt a pixel) at (300, 0).
fn cmyk_doc_with_image(px: &[[u8; 4]]) -> Session {
let mut s = Session::new();
+81
View File
@@ -4109,6 +4109,17 @@ fn area_to_point_turns_wraps_into_breaks() {
assert_eq!(txt.replace('\n', " "), "one two three four five six");
}
/// Convert To Point Type keeps the lines that a paragraph return or a forced line break (U+2028)
/// starts as they are: neither gets a paragraph return added after it.
#[test]
fn area_to_point_keeps_forced_line_breaks() {
let mut s = session();
let a = id_of(&s.execute("text.create", &json!({"x": 0, "y": 0, "text": "ab\u{2028}c\nd", "area": {"width": 300, "height": 200}})).unwrap());
sel(&mut s, &[a]);
s.execute("type.convertToPointType", &json!({})).unwrap();
assert_eq!(plain(&s, a), "ab\u{2028}c\nd");
}
#[test]
fn placeholder_and_insert_characters() {
let mut s = session();
@@ -4124,6 +4135,76 @@ fn placeholder_and_insert_characters() {
assert!(s.execute("type.insert", &json!({"char": "nope"})).is_err());
}
/// Type › Insert Break Character › Forced Line Break (`type.insert {char: "forcedLineBreak"}`)
/// starts a new line in the same paragraph (U+2028, as Shift+Enter types it), so the paragraph's
/// space before does not come between the two lines; `paragraphReturn` starts a new paragraph.
/// Each insert is one undo step.
#[test]
fn insert_forced_line_break_differs_from_paragraph_return() {
fn second_line_gap(s: &Session, id: NodeId) -> f64 {
let NodeKind::Text(t) = &node(s, id).kind else { panic!("not text") };
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
assert_eq!(lay.lines.len(), 2, "{:?}", t.plain_text());
lay.lines[1].baseline - lay.lines[0].baseline
}
let mut s = session();
let mut gaps = Vec::new();
for (c, want) in [("forcedLineBreak", "ab\u{2028}c"), ("paragraphReturn", "ab\nc")] {
let t = text(&mut s, "ab");
sel(&mut s, &[t]);
s.execute("text.setFormat", &json!({"ids": [t.0], "spaceBefore": 30})).unwrap();
let steps = undo_len(&s);
s.execute("type.insert", &json!({"char": c})).unwrap();
assert_eq!(undo_len(&s), steps + 1, "{c}");
s.execute("type.insert", &json!({"text": "c"})).unwrap();
assert_eq!(plain(&s, t), want, "{c}");
gaps.push(second_line_gap(&s, t));
}
assert!(gaps[1] - gaps[0] > 29.0, "space before only at the paragraph return: {gaps:?}");
// The same character by `unicode` and by `text`.
let t = text(&mut s, "");
sel(&mut s, &[t]);
s.execute("type.insert", &json!({"unicode": "2028"})).unwrap();
s.execute("type.insert", &json!({"text": "\u{2028}"})).unwrap();
assert_eq!(plain(&s, t), "\u{2028}\u{2028}");
}
/// While the Type tool edits text, the Insert Special, Whitespace and Break menu items
/// (`type.insert` without `ids`) insert at its caret or replace its selection, as one undo step,
/// and the caret goes after the insertion; `ids` still appends to those objects.
#[test]
fn insert_character_goes_to_the_type_tool_caret() {
use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey};
let mut s = session();
let v = ViewInfo::default();
s.select_tool("type", v).unwrap();
for k in [PointerKind::Down, PointerKind::Up] {
s.pointer(&PointerEvent::new(k, 50.0, 300.0), v).unwrap();
}
let t = s.doc().unwrap().selection.objects[0];
s.tool_text("abcd", v).unwrap();
for _ in 0..2 {
s.tool_key(ToolKey::Left, Mods::default(), v).unwrap();
}
let steps = undo_len(&s);
s.execute("type.insert", &json!({"text": ""})).unwrap();
assert_eq!(undo_len(&s), steps, "an empty insert changes nothing");
s.execute("type.insert", &json!({"char": "forcedLineBreak"})).unwrap();
assert_eq!(plain(&s, t), "ab\u{2028}cd");
assert_eq!(s.tool_options()["caret"], json!(5));
s.tool_text("X", v).unwrap();
assert_eq!(plain(&s, t), "ab\u{2028}Xcd");
s.tool_key(ToolKey::Left, Mods { shift: true, ..Mods::default() }, v).unwrap();
s.execute("type.insert", &json!({"char": "paragraphReturn"})).unwrap();
assert_eq!(plain(&s, t), "ab\u{2028}\ncd");
s.execute("type.insert", &json!({"ids": [t.0], "text": "!"})).unwrap();
assert_eq!(plain(&s, t), "ab\u{2028}\ncd!");
s.tool_key(ToolKey::Escape, Mods::default(), v).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(plain(&s, t), "ab\u{2028}Xcd", "the replacement is one undo step");
}
/// `type.insert` by code (#5108): `code` as a Windows Alt+0 code types (Windows-1252 for
/// 128–159, the code point otherwise), `unicode` as a hex code point.
#[test]
+2 -2
View File
@@ -393,10 +393,10 @@ fn a_group_selection_marquee_leaves_out_a_drop_shadow() {
run(&mut s, "select.none", json!({}));
let sel = marquee(&mut s, "groupSelection", (85.0, 40.0), (95.0, 60.0));
assert!(sel.objects.is_empty() && sel.anchors.is_empty(), "{sel:?}");
// Over the shadow and B's upper left corner: that anchor of B.
// Over the shadow and B's upper left corner: B whole, and not A (#8047).
let sel = marquee(&mut s, "groupSelection", (90.0, 5.0), (105.0, 30.0));
assert_eq!(sel.objects, [b]);
assert_eq!(picked_points(&s, b), [Point::new(100.0, 20.0)]);
assert!(sel.partial(b).is_none(), "{sel:?}");
// With E, a marquee around B that crosses A's shadow selects B whole, and not A.
run(&mut s, "select.none", json!({}));
let v = ViewInfo::default();
+35
View File
@@ -2289,6 +2289,41 @@ fn threaded_list_edited_in_its_second_frame() -> (Session, NodeId, NodeId, Strin
(s, a, b, story)
}
/// Type › Insert Break Character › Forced Line Break (`type.insert`) after Select All in threaded
/// text replaces the whole story, every frame's text, as one undo step.
#[test]
fn insert_character_replaces_the_whole_story_that_select_all_selected() {
let (mut s, a, b, story) = threaded_story_edited_in_its_second_frame();
s.execute("select.all", &json!({})).unwrap();
let steps = undo_labels(&s).len();
s.execute("type.insert", &json!({"char": "forcedLineBreak"})).unwrap();
assert_eq!(undo_labels(&s).len(), steps + 1, "one undo step");
assert_eq!(format!("{}{}", obj(&s, a).plain_text(), obj(&s, b).plain_text()), "\u{2028}");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(format!("{}{}", obj(&s, a).plain_text(), obj(&s, b).plain_text()), story);
}
/// When `type.insert` at the caret in the first frame of threaded text pushes the caret's place on
/// into the next frame, the Type tool's caret goes there with it, and typing goes after the
/// insertion.
#[test]
fn insert_character_moves_the_caret_with_the_text_it_flows_on() {
let (mut s, a, b, story) = threaded_story_edited_in_its_second_frame();
let first = obj(&s, a).plain_text();
// Before the last word of the first frame: two line breaks there push the line after the
// first one on into the second frame.
let at = first.trim_end().rfind(' ').map_or(0, |k| k + 1);
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
s.set_tool_option("textSelection", &json!({"editing": a.0, "anchor": at, "caret": at}));
for _ in 0..2 {
s.execute("type.insert", &json!({"char": "forcedLineBreak"})).unwrap();
}
assert!(obj(&s, a).plain_text().len() < at + 6, "the second break flows on into the second frame");
s.tool_text("X", ViewInfo::default()).unwrap();
let want = format!("{}\u{2028}\u{2028}X{}", &story[..at], &story[at..]);
assert_eq!(format!("{}{}", obj(&s, a).plain_text(), obj(&s, b).plain_text()), want);
}
#[test]
fn remove_breaks_takes_the_whole_story_that_select_all_selected() {
let (mut s, a, b, story) = threaded_list_edited_in_its_second_frame();
+4 -2
View File
@@ -1255,9 +1255,11 @@ fn direct_selection_shift_marquee_toggles_anchors() {
let st = s.doc().unwrap();
assert_eq!(st.selection.objects, vec![a]);
assert_eq!(st.selection.partial(a), None);
// Group Selection's marquee toggles the same way.
// Group Selection's marquee toggles the paths it touches whole: a leaves, b joins (#8047).
gesture(&mut s, "groupSelection", &top, shift);
assert_eq!(s.doc().unwrap().selection.partial(a).map(|p| p.len()), Some(2));
let st = s.doc().unwrap();
assert_eq!(st.selection.objects, vec![b]);
assert_eq!(st.selection.partial(b), None);
}
/// The Lasso: Shift adds anchors, Alt takes them away, and neither drops the rest of the
+23 -1
View File
@@ -173,6 +173,12 @@ impl Session {
let text_selection = ((id == "eyedropper" && is_type(self.tool.id())) || (self.tool.id() == "eyedropper" && is_type(id)))
.then(|| self.tool.options())
.filter(|o| o.get("editing").is_some_and(|v| !v.is_null()) && o.get("start") != o.get("end"));
// The gradient mesh points the Mesh tool, Direct Selection or the Lasso picked stay picked
// for the Eyedropper, which samples into them (#8090), and for the tool after it.
let mesh_points = (id == "eyedropper" || self.tool.id() == "eyedropper")
.then(|| self.tool.options().get("meshPoints").cloned())
.flatten()
.filter(|v| v.as_array().is_some_and(|a| !a.is_empty()));
let acts = self.with_tool_cx(view, |t, cx| t.deactivate(cx));
self.apply_actions(acts)?;
self.keep_tool_settings();
@@ -180,6 +186,9 @@ impl Session {
if let Some(selection) = text_selection {
self.tool.set_option("textSelection", &selection);
}
if let Some(points) = mesh_points {
self.tool.set_option("meshPoints", &points);
}
if vectorcraft_tools::catalog::is_selection_tool(id) {
self.last_selection_tool = Some(self.tool.id());
self.select_whole_instance(id);
@@ -258,7 +267,13 @@ impl Session {
// The lending tool does not see the press: it counts as a press elsewhere for the clicks a
// double-click or triple-click compares.
self.tool.press_elsewhere();
let lent = self.make_tool(id);
let mut lent = self.make_tool(id);
// The gradient mesh points the Eyedropper holds are the lent tool's picks, which a Shift
// click adds to (#8090).
if self.tool.id() == "eyedropper" {
let points = self.tool.options().get("meshPoints").cloned().unwrap_or_else(|| Value::Array(vec![]));
lent.set_option("meshPoints", &points);
}
self.selection_at_lend = self.active().map(|d| (d.uid, d.selection.clone()));
self.lender = Some(std::mem::replace(&mut self.tool, lent));
Ok((PointerEvent { mods: Mods { cmd: false, ..ev.mods }, ..*ev }, settled))
@@ -269,10 +284,17 @@ impl Session {
/// Cmd+click that takes the type being edited out of the selection ends its edit (#3779).
pub(crate) fn give_back_tool(&mut self, view: ViewInfo) -> Result<()> {
let Some(lender) = self.lender.take() else { return Ok(()) };
// The points the lent tool left picked go back to the Eyedropper, none when it unpicked
// them all (#8090). Group Selection picks no mesh points, so the Eyedropper keeps its own.
let mesh_points =
(lender.id() == "eyedropper" && self.tool.id() != "groupSelection").then(|| self.tool.options().get("meshPoints").cloned()).flatten();
let acts = self.with_tool_cx(view, |t, cx| t.deactivate(cx));
let r = self.apply_actions(acts);
self.keep_tool_settings();
self.tool = lender;
if let Some(points) = mesh_points {
self.tool.set_option("meshPoints", &points);
}
// A gesture that left the selection as it found it (a Shift marquee over nothing) picked
// nothing: the selection keeps what it was, the Pen's last anchor or an earlier pick.
let left = self.active().map(|d| (d.uid, d.selection.clone()));
@@ -61,6 +61,20 @@ fn selection_commands_report_the_resulting_selection() {
}
}
#[test]
fn toggle_and_add_handle_each_listed_id_in_order() {
let (mut s, a, b) = session();
let c = NodeId(s.execute("shape.rectangle", &json!({"x": 40, "y": 0, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap());
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
// `a` goes off and back on at the end, `b` goes off, and `c` comes on.
assert_eq!(s.execute("select.toggle", &json!({"ids": [a.0, b.0, c.0, a.0]})).unwrap(), json!({"count": 2, "ids": [c.0, a.0]}));
assert_eq!(s.execute("select.add", &json!({"ids": [b.0, a.0, b.0]})).unwrap(), json!({"count": 3, "ids": [c.0, a.0, b.0]}));
// Inverse selects the objects that were not selected, in document order.
s.execute("select.set", &json!({"ids": [b.0]})).unwrap();
s.execute("select.inverse", &json!({})).unwrap();
assert_eq!(s.active().unwrap().selection.objects, [a, c]);
}
#[test]
fn single_id_toggle_validates_before_mutating() {
let (mut s, a, _) = session();
+308
View File
@@ -386,6 +386,246 @@ fn rgb_values_are_written_again_unchanged_in_a_wide_gamut_working_space() {
same_lines(&again.lines().map(String::from).collect::<Vec<_>>(), &first.lines().map(String::from).collect::<Vec<_>>());
}
/// With a working RGB space other than sRGB, type's RGB fill and stroke are written in the text
/// document with their working RGB values, so they read back as the same colors.
#[test]
fn type_rgb_paints_read_back_unchanged_in_a_wide_gamut_working_space() {
const CHILD: &str = "VECTORCRAFT_TEST_AI_EDITING_WIDE_GAMUT_TYPE";
if std::env::var_os(CHILD).is_none() {
// Color settings are process-wide: exercise this profile in a separate test process.
let output = std::process::Command::new(std::env::current_exe().unwrap())
.args(["--exact", "ai_editing::tests::type_rgb_paints_read_back_unchanged_in_a_wide_gamut_working_space", "--nocapture"])
.env(CHILD, "1")
.output()
.unwrap();
let stdout = String::from_utf8_lossy(&output.stdout);
assert!(
output.status.success() && stdout.contains("test result: ok. 1 passed; 0 failed;"),
"isolated color profile test failed:\n{stdout}\n{}",
String::from_utf8_lossy(&output.stderr),
);
return;
}
use vectorcraft_color::cms;
use vectorcraft_doc::{CharStyle, TextObject};
cms::set_active(&cms::ColorSettings { rgb: cms::WIDE_GAMUT_RGB.into(), ..Default::default() }).unwrap();
assert!(!cms::active().rgb_is_srgb());
let mut doc = Document::new(300.0, 200.0);
let layer = doc.layers[0].id;
let (fill, stroke) = (Color::rgb(0.8, 0.4, 0.2), Color::rgb(0.1, 0.7, 0.3));
let st = CharStyle { stroke: solid(stroke), stroke_width: 1.0, ..style(14.0, fill) };
let n = text_node(&mut doc, TextObject::point(vectorcraft_geom::Point::new(20.0, 40.0), "Wide", st));
doc.insert(Some(layer), usize::MAX, n).unwrap();
let back = read_back(&doc);
let paints: Vec<(Paint, Paint)> = back.layers[0]
.children()
.unwrap()
.iter()
.filter_map(|n| if let NodeKind::Text(t) = &n.kind { Some(t) } else { None })
.flat_map(|t| t.runs.iter().map(|r| (r.style.fill.clone(), r.style.stroke.clone())))
.collect();
assert!(!paints.is_empty(), "the type is read back as type");
let near = |p: &Paint, want: Color| match (p, want) {
(Paint::Solid { color: Color::Rgb { r, g, b }, .. }, Color::Rgb { r: wr, g: wg, b: wb }) => {
(r - wr).abs() < 1e-4 && (g - wg).abs() < 1e-4 && (b - wb).abs() < 1e-4
}
_ => false,
};
for (f, s) in &paints {
assert!(near(f, fill), "fill {f:?} reads back as {fill:?}");
assert!(near(s, stroke), "stroke {s:?} reads back as {stroke:?}");
}
}
/// With a working RGB space other than sRGB, a Lab fill, a Lab gradient stop, type filled with a
/// Lab color and a freeform gradient's average color are written as RGB values in the working RGB
/// space, so they read back as RGB colors that show as the colors they were written for.
#[test]
fn lab_paints_read_back_as_the_same_color_in_a_wide_gamut_working_space() {
const CHILD: &str = "VECTORCRAFT_TEST_AI_EDITING_WIDE_GAMUT_LAB";
if std::env::var_os(CHILD).is_none() {
// Color settings are process-wide: exercise this profile in a separate test process.
let output = std::process::Command::new(std::env::current_exe().unwrap())
.args(["--exact", "ai_editing::tests::lab_paints_read_back_as_the_same_color_in_a_wide_gamut_working_space", "--nocapture"])
.env(CHILD, "1")
.output()
.unwrap();
let stdout = String::from_utf8_lossy(&output.stdout);
assert!(
output.status.success() && stdout.contains("test result: ok. 1 passed; 0 failed;"),
"isolated color profile test failed:\n{stdout}\n{}",
String::from_utf8_lossy(&output.stderr),
);
return;
}
use vectorcraft_color::cms;
use vectorcraft_doc::TextObject;
cms::set_active(&cms::ColorSettings { rgb: cms::WIDE_GAMUT_RGB.into(), ..Default::default() }).unwrap();
assert!(!cms::active().rgb_is_srgb());
let (fill, stop, ink) = (Color::lab(60.0, 20.0, -30.0), Color::lab(45.0, -25.0, 15.0), Color::lab(70.0, 10.0, 40.0));
let mut doc = Document::new(300.0, 200.0);
let layer = doc.layers[0].id;
let n = square(&mut doc, Rect::new(10.0, 10.0, 30.0, 30.0), fill);
doc.insert(Some(layer), usize::MAX, n).unwrap();
let stops = vec![GradientStop::new(0.0, Color::rgb(0.1, 0.7, 0.3)), GradientStop::new(1.0, stop)];
let paint = gradient_paint(Gradient::new(GradientKind::Linear, stops), None, None);
let n = painted(&mut doc, shapes::rectangle(Rect::new(40.0, 10.0, 60.0, 30.0)), vec![AppearanceItem::Fill(FillLayer::new(paint))]);
doc.insert(Some(layer), usize::MAX, n).unwrap();
let n = text_node(&mut doc, TextObject::point(vectorcraft_geom::Point::new(20.0, 80.0), "Lab", style(14.0, ink)));
doc.insert(Some(layer), usize::MAX, n).unwrap();
// A freeform gradient is written as the average of its stops' display colors.
let (a, b) = (Color::rgb(0.9, 0.2, 0.1), Color::lab(50.0, -40.0, -20.0));
let free = ramp(GradientKind::Freeform, &[(0.0, a, 1.0, 0.5), (1.0, b, 1.0, 0.5)]);
let n = painted(
&mut doc,
shapes::rectangle(Rect::new(70.0, 10.0, 90.0, 30.0)),
vec![AppearanceItem::Fill(FillLayer::new(gradient_paint(free, None, None)))],
);
doc.insert(Some(layer), usize::MAX, n).unwrap();
let average = {
let (a, b) = (a.to_rgb(), b.to_rgb());
[0, 1, 2].map(|i| (a[i] + b[i]) / 2.0)
};
let back = read_back(&doc);
let shows_as = |got: Color, want: [f32; 3], what: &str| {
assert!(matches!(got, Color::Rgb { .. }), "{what} reads back as RGB: {got:?}");
let g = got.to_rgb();
assert!(g.iter().zip(want).all(|(a, b)| (a - b).abs() < 2e-3), "{what} {got:?} shows as {g:?}, not {want:?}");
};
let mut solids = vec![(fill.to_rgb(), "fill"), (average, "freeform gradient's average")].into_iter();
let (mut stops, mut runs) = (0, 0);
for n in back.layers[0].children().unwrap() {
match (&n.kind, n.appearance.fill_paint()) {
(NodeKind::Text(t), _) => {
for r in &t.runs {
let Paint::Solid { color, .. } = r.style.fill else { panic!("type fill {:?}", r.style.fill) };
shows_as(color, ink.to_rgb(), "type fill");
runs += 1;
}
}
(_, Paint::Solid { color, .. }) => {
let Some((want, what)) = solids.next() else { panic!("unexpected solid {color:?}") };
shows_as(color, want, what);
}
(_, Paint::Gradient(g)) => {
let last = g.gradient.stops.last().unwrap();
shows_as(last.color, stop.to_rgb(), "gradient stop");
stops += 1;
}
(_, p) => panic!("unexpected paint {p:?}"),
}
}
assert_eq!((solids.len(), stops), (0, 1));
assert!(runs > 0, "the type is read back as type");
}
/// With a working RGB space other than sRGB, the average color written for a gradient along a
/// stroke and for a gradient that can't be placed, a stop of a spot color defined in Lab and type
/// stroked with a Lab color are written as RGB values in the working RGB space, so each reads back
/// as an RGB color that shows as the color it was written for.
#[test]
fn averages_lab_spot_stops_and_lab_type_strokes_read_back_as_the_same_color_in_a_wide_gamut_working_space() {
const CHILD: &str = "VECTORCRAFT_TEST_AI_EDITING_WIDE_GAMUT_AVERAGES";
if std::env::var_os(CHILD).is_none() {
// Color settings are process-wide: exercise this profile in a separate test process.
let output = std::process::Command::new(std::env::current_exe().unwrap())
.args([
"--exact",
"ai_editing::tests::averages_lab_spot_stops_and_lab_type_strokes_read_back_as_the_same_color_in_a_wide_gamut_working_space",
"--nocapture",
])
.env(CHILD, "1")
.output()
.unwrap();
let stdout = String::from_utf8_lossy(&output.stdout);
assert!(
output.status.success() && stdout.contains("test result: ok. 1 passed; 0 failed;"),
"isolated color profile test failed:\n{stdout}\n{}",
String::from_utf8_lossy(&output.stderr),
);
return;
}
use vectorcraft_color::cms;
use vectorcraft_color::gradient::GradientGeom;
use vectorcraft_doc::{CharStyle, TextObject};
cms::set_active(&cms::ColorSettings { rgb: cms::WIDE_GAMUT_RGB.into(), ..Default::default() }).unwrap();
assert!(!cms::active().rgb_is_srgb());
let shows_as = |got: Color, want: [f32; 3], what: &str| {
assert!(matches!(got, Color::Rgb { .. }), "{what} reads back as RGB: {got:?}");
let g = got.to_rgb();
assert!(g.iter().zip(want).all(|(a, b)| (a - b).abs() < 2e-3), "{what} {got:?} shows as {g:?}, not {want:?}");
};
let (a, b) = (Color::rgb(0.9, 0.2, 0.1), Color::lab(50.0, -40.0, -20.0));
let average = {
let (a, b) = (a.to_rgb(), b.to_rgb());
[0, 1, 2].map(|i| (a[i] + b[i]) / 2.0)
};
// Every solid paint of the art read back, in order.
let solids = |doc: &Document| {
let mut out = vec![];
read_back(doc).walk(|n| {
if matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) {
out.extend(n.appearance.items.iter().filter_map(|i| match i.paint() {
Paint::Solid { color, .. } => Some(*color),
_ => None,
}));
}
});
out
};
// A gradient along a stroke: the stroke's outline in its average color.
let mut doc = Document::new(200.0, 100.0);
let layer = doc.layers[0].id;
let mut st = StrokeLayer::new(gradient_paint(ramp(GradientKind::Linear, &[(0.0, a, 1.0, 0.5), (1.0, b, 1.0, 0.5)]), None, None), 4.0);
st.gradient_mode = vectorcraft_doc::StrokeGradientMode::Along;
let n = painted(&mut doc, shapes::rectangle(Rect::new(10.0, 10.0, 30.0, 30.0)), vec![AppearanceItem::Stroke(st)]);
doc.insert(Some(layer), usize::MAX, n).unwrap();
let [got] = solids(&doc)[..] else { panic!("one solid paint: {:?}", solids(&doc)) };
shows_as(got, average, "a gradient along a stroke");
// A radial gradient flattened to a line: its average color.
let flat = GradientGeom { start: (20.0, 20.0).into(), end: (40.0, 20.0).into(), aspect: 0.0, focal: None };
let radial = ramp(GradientKind::Radial, &[(0.0, a, 1.0, 0.5), (1.0, b, 1.0, 0.5)]);
let doc = one_object(
shapes::rectangle(Rect::new(10.0, 10.0, 50.0, 50.0)),
vec![AppearanceItem::Fill(FillLayer::new(gradient_paint(radial, Some(flat), None)))],
);
let [got] = solids(&doc)[..] else { panic!("one solid paint: {:?}", solids(&doc)) };
shows_as(got, average, "a gradient that can't be placed");
// A stop of a spot color defined in Lab, at full strength.
let moss = Color::lab(55.0, -30.0, 20.0);
let mut doc = Document::new(200.0, 100.0);
let mut swatches: Vec<Swatch> = doc.swatches.iter().cloned().collect();
swatches.push(Swatch { name: "Moss".into(), paint: solid(moss), global: true, spot: true });
doc.swatches = swatches.into();
let layer = doc.layers[0].id;
let stops = vec![GradientStop::new(0.0, Color::rgb(0.1, 0.2, 0.3)), GradientStop { swatch: Some("Moss".into()), ..GradientStop::new(1.0, moss) }];
let fill = gradient_paint(Gradient::new(GradientKind::Linear, stops), None, None);
let n = painted(&mut doc, shapes::rectangle(Rect::new(10.0, 10.0, 30.0, 30.0)), vec![AppearanceItem::Fill(FillLayer::new(fill))]);
doc.insert(Some(layer), usize::MAX, n).unwrap();
let back = read_back(&doc);
let Paint::Gradient(g) = back.layers[0].children().unwrap()[0].appearance.fill_paint() else { panic!("a gradient") };
shows_as(g.gradient.stops.last().unwrap().color, moss.to_rgb(), "a Lab spot color's stop");
// Type stroked with a Lab color.
let ink = Color::lab(40.0, 30.0, -50.0);
let mut doc = Document::new(200.0, 100.0);
let layer = doc.layers[0].id;
let st = CharStyle { stroke: solid(ink), stroke_width: 1.0, ..style(14.0, Color::rgb(0.8, 0.4, 0.2)) };
let n = text_node(&mut doc, TextObject::point(vectorcraft_geom::Point::new(20.0, 40.0), "Lab", st));
doc.insert(Some(layer), usize::MAX, n).unwrap();
let back = read_back(&doc);
let mut runs = 0;
for n in back.layers[0].children().unwrap() {
if let NodeKind::Text(t) = &n.kind {
for r in &t.runs {
let Paint::Solid { color, .. } = r.style.stroke else { panic!("type stroke {:?}", r.style.stroke) };
shows_as(color, ink.to_rgb(), "type stroke");
runs += 1;
}
}
}
assert!(runs > 0, "the type is read back as type");
}
/// A gradient stop of a Lab spot color writes the RGB values of the Lab values as written (to four
/// decimals, clamped to the range a reader reads), the same Lab values its CMYK equivalent and the
/// palette's definition come from: for Lab values of many decimals and for Lab values out of range.
@@ -9028,6 +9268,74 @@ fn a_link_to_a_twist_style_is_kept_where_the_reader_reads_it() {
}
}
/// A link to a graphic style with Transform or Free Distort is kept where the reader reads the
/// effect. On a compound path of a square and a guide: Transform with the guide inside the square,
/// moving only, or with Transform Objects off (Transform Patterns on or off), and Free Distort. On a
/// group holding such a compound path: Transform with the guide inside. Transform that scales where
/// the guide reaches past the square is written without the link and warns.
#[test]
fn a_link_to_a_transform_or_free_distort_style_with_a_guide_is_kept_where_the_reader_reads_it() {
// A compound path of a filled square and a guide from `a` to `b`, with appearance `ap`.
fn guided(doc: &mut Document, ap: Appearance, a: (f64, f64), b: (f64, f64)) -> Node {
let square = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(10.0, 10.0, 50.0, 40.0)), Appearance::default());
let path = shapes::rectangle(Rect::new(a.0, a.1, b.0, b.1));
let guide = Node::new(doc.alloc_id(), NodeKind::Path { path, rule: FillRule::NonZero, live: None, clipping: false, guide: true });
let mut n = Node::new(doc.alloc_id(), NodeKind::Compound { children: vec![Arc::new(square), Arc::new(guide)], rule: FillRule::NonZero });
n.appearance = ap.into();
n
}
// A document with that compound path (in a group when `grouped`) with effect `e`, linked to a
// graphic style of that appearance.
let make = |e: vectorcraft_doc::Effect, grouped: bool, a: (f64, f64), b: (f64, f64)| {
let mut doc = Document::new(200.0, 100.0);
let filled = Appearance::basic(black_fill(), Paint::None, 0.0);
let ap = Appearance { effects: vec![e], ..if grouped { Appearance::default() } else { filled.clone() } };
let mut g = vectorcraft_doc::GraphicStyle::new("Moved", ap.clone());
g.id = 9;
doc.graphic_styles.push(g);
let mut n = if grouped {
let member = guided(&mut doc, filled, a, b);
let mut n = Node::group(doc.alloc_id(), vec![Arc::new(member)]);
n.appearance = ap.into();
n
} else {
guided(&mut doc, ap, a, b)
};
n.extras_mut().graphic_style = Some(9);
put(&mut doc, n);
doc
};
let scale = || fx("distort.transform", serde_json::json!({"copies": 0, "scaleH": 50.0, "scaleV": 50.0}));
let moved = || fx("distort.transform", serde_json::json!({"copies": 0, "moveH": 5.0}));
let in_place = || fx("distort.transform", serde_json::json!({"copies": 0, "scaleH": 50.0, "objects": false, "patterns": false}));
let patterns_only = || fx("distort.transform", serde_json::json!({"copies": 0, "scaleH": 50.0, "objects": false, "patterns": true}));
let slant = || fx("distort.freeDistort", serde_json::json!({"corners": [[0.2, 0.0], [1.2, 0.0], [1.0, 1.0], [0.0, 1.0]]}));
let (inside, past) = (((20.0, 20.0), (30.0, 30.0)), ((20.0, 20.0), (90.0, 30.0)));
for (what, doc, id, kept) in [
("a compound path scaled, its guide inside", make(scale(), false, inside.0, inside.1), "distort.transform", true),
("a compound path moved, its guide past", make(moved(), false, past.0, past.1), "distort.transform", true),
("a compound path scaled with Transform Objects off, its guide past", make(in_place(), false, past.0, past.1), "distort.transform", true),
(
"a compound path scaled with Transform Objects off and Transform Patterns on, its guide past",
make(patterns_only(), false, past.0, past.1),
"distort.transform",
true,
),
("a compound path distorted, its guide past", make(slant(), false, past.0, past.1), "distort.freeDistort", true),
("a group scaled, its guide inside", make(scale(), true, inside.0, inside.1), "distort.transform", true),
("a compound path scaled, its guide past", make(scale(), false, past.0, past.1), "distort.transform", false),
("a group scaled, its guide past", make(scale(), true, past.0, past.1), "distort.transform", false),
] {
let out = export_ai_editing(&doc, &opts()).unwrap();
assert_eq!(out.warnings.iter().any(|w| w == writer::STYLE_LINKS), !kept, "{what}: {:?}", out.warnings);
let back = read_back(&doc);
let n = &back.layers[0].children().unwrap()[0];
let style = n.extras().graphic_style.and_then(|id| back.graphic_style_by_id(id)).map(|g| g.name.as_str());
assert_eq!(style, kept.then_some("Moved"), "{what}: {n:?}");
assert_eq!(n.appearance.effects.iter().any(|e| e.id == id), kept, "{what}: {n:?}");
}
}
/// Twist and Transform on an object that isn't linked to a graphic style are not written as a style
/// of its own: the object reads back without live effects.
#[test]
+2 -2
View File
@@ -1747,8 +1747,8 @@ impl<'a> Writer<'a> {
self.plain_color(*color, stroke);
}
/// A color that names no swatch: `g` (gray), `k` (CMYK), else `c m y k r g b Xa` (RGB in the
/// working RGB space, and Lab as display RGB), with its CMYK equivalent (an RGB color's from its
/// A color that names no swatch: `g` (gray), `k` (CMYK), else `c m y k r g b Xa` (RGB, and Lab
/// as RGB, in the working RGB space), with its CMYK equivalent (an RGB color's from its
/// values as written, a Lab color's from its Lab values).
fn plain_color(&mut self, color: Color, stroke: bool) {
let s = &mut self.body;
+2 -2
View File
@@ -417,8 +417,8 @@ impl Writer<'_> {
/// A stop's color and its style: gray `lightness 0`, CMYK `c m y k 1`, RGB (and Lab, as RGB)
/// `c m y k r g b 2` with its CMYK equivalent; a spot color its full color's CMYK equivalent,
/// then its RGB values when it isn't CMYK, its name and how much lighter than the full color,
/// then `3` (CMYK), or `1 4` (RGB, and Lab as RGB). RGB values are an RGB color's own (in the
/// working RGB space) and a Lab color's display RGB ([`ai_ops::rgb_values`]). An RGB color's CMYK
/// then `3` (CMYK), or `1 4` (RGB, and Lab as RGB). RGB values are in the working RGB space: an
/// RGB color's own and a Lab color's converted ([`ai_ops::rgb_values`]). An RGB color's CMYK
/// equivalent is converted from its values as written ([`ai_ops::as_written`]), a Lab color's
/// from its Lab values, and a spot color's CMYK equivalent and RGB values both come from its full
/// color as the palette writes it.
+4 -2
View File
@@ -28,7 +28,7 @@ use vectorcraft_doc::{
};
use vectorcraft_geom::{Affine, PathData, Point};
use crate::ps;
use crate::{ai_ops, ps};
/// What the text document holds of type, and what it leaves out.
pub(in crate::ai_editing) const TYPE_ATTRIBUTES: &str = "attributes of type other than its font, size, leading, tracking, baseline shift, horizontal and vertical scale, solid fill, solid stroke and its weight, cap, join and miter limit, capitals, small capitals at the document's size, Tate-chu-yoko, Standard Vertical Roman Alignment, Insert Aki, paragraph alignment, indents, space before and after, hyphenation on or off, right-to-left direction, Kinsoku set, Kinsoku Shori Type, Burasagari and Bunri-Kinshi (for example underline, kerning, OpenType features, swatch links of its colors, character and paragraph styles, tabs, lists, optical margin alignment, area type's inset spacing, vertical alignment and flow, a minimum first baseline with the Ascent first baseline, and type on a path's effect, alignment and spacing and an end bracket at the very end of an open path) are left out of the editing data for other apps";
@@ -176,11 +176,13 @@ fn set(resources: Vec<V>, display: bool) -> V {
}
/// A paint: kind 0 gray (`[alpha, lightness]`), 1 RGB, 2 CMYK, as the reader's `paint` reads them.
/// RGB values are an RGB color's own (in the working RGB space) and a Lab color's converted into
/// the working RGB space ([`ai_ops::rgb_values`]).
fn paint(c: &Color) -> V {
let (kind, values) = match *c {
Color::Gray { k } => (0, vec![1.0 - f64::from(k.clamp(0.0, 1.0))]),
Color::Cmyk { c, m, y, k } => (2, [c, m, y, k].iter().map(|v| f64::from(v.clamp(0.0, 1.0))).collect()),
Color::Rgb { .. } | Color::Lab { .. } => (1, c.to_rgb().iter().map(|v| f64::from(v.clamp(0.0, 1.0))).collect()),
Color::Rgb { .. } | Color::Lab { .. } => (1, ai_ops::rgb_values(*c).iter().map(|v| f64::from(*v)).collect()),
};
let values: Vec<f64> = std::iter::once(1.0).chain(values).collect();
dict(vec![(99, V::Name("SimplePaint")), (0, dict(vec![(0, V::Int(kind)), (1, reals(&values))]))])
+8 -5
View File
@@ -113,20 +113,23 @@ pub(crate) fn as_written(color: Color) -> Color {
}
}
/// The RGB values written for `color`, clamped to 0..1: an RGB color's own values (in the working
/// RGB space, as a reader reads them back), any other color's display RGB.
/// The RGB values written for `color`, clamped to 0..1, in the working RGB space, as a reader
/// reads them back: an RGB color's own values, any other color's display RGB converted into the
/// working RGB space.
pub(crate) fn rgb_values(color: Color) -> [f32; 3] {
match color {
Color::Rgb { r, g, b } => [r, g, b].map(unit),
c => c.to_rgb().map(unit),
c => vectorcraft_color::cms::active().srgb_to_rgb(c.to_rgb()).map(unit),
}
}
/// The average colour of a gradient's stops (in RGB).
/// The average color of a gradient's stops: the average of their display RGB, as an RGB color in
/// the working RGB space.
pub(crate) fn average(g: &Gradient) -> Color {
let n = g.stops.len().max(1) as f32;
let sum = g.stops.iter().map(|s| s.color.to_rgb()).fold([0.0f32; 3], |a, c| [a[0] + c[0], a[1] + c[1], a[2] + c[2]]);
Color::rgb(unit(sum[0] / n), unit(sum[1] / n), unit(sum[2] / n))
let [r, green, b] = vectorcraft_color::cms::active().srgb_to_rgb(sum.map(|v| v / n)).map(unit);
Color::rgb(r, green, b)
}
/// The pixels an image's part keeps past the edge of the region that shows it, on each side: as
+53 -13
View File
@@ -1126,13 +1126,47 @@ fn no_guides(n: &Node, depth: usize) -> bool {
depth <= MAX_DEPTH && !n.is_guide() && n.children().into_iter().flatten().all(|c| no_guides(c, depth + 1))
}
/// Is `n` a compound path with a guide member whose bounds reach past the bounds of its members that
/// aren't guides, or with guide members only? Any other object counts as no.
/// Is `n` a compound path or group with a guide in it whose bounds reach past the bounds of the rest
/// of its art, or with guides only? Members are looked into to [`MAX_DEPTH`]; deeper counts as yes.
/// Any other object counts as no.
fn guides_reach_past(n: &Node) -> bool {
let NodeKind::Compound { children, .. } = &n.kind else { return false };
let bounds =
|guides: bool| children.iter().filter(|c| c.is_guide() == guides).fold(None, |acc, c| vectorcraft_geom::union_opt(acc, c.geometric_bounds()));
bounds(true).is_some_and(|g| bounds(false).is_none_or(|o| o.union(g) != o))
/// Adds the bounds of the guides in `n`'s members to `guides` and of the rest to `art`; false when
/// it is deeper than [`MAX_DEPTH`].
fn split(n: &Node, depth: usize, guides: &mut Option<Rect>, art: &mut Option<Rect>) -> bool {
depth <= MAX_DEPTH
&& n.children().into_iter().flatten().all(|c| match c.children() {
_ if c.is_guide() => {
*guides = vectorcraft_geom::union_opt(*guides, c.geometric_bounds());
true
}
Some(_) => split(c, depth + 1, guides, art),
None => {
*art = vectorcraft_geom::union_opt(*art, c.geometric_bounds());
true
}
})
}
if !matches!(n.kind, NodeKind::Compound { .. } | NodeKind::Group { .. }) {
return false;
}
let (mut guides, mut art) = (None, None);
!split(n, 0, &mut guides, &mut art) || guides.is_some_and(|g| art.is_none_or(|o| o.union(g) != o))
}
/// Do Transform params `p` scale, turn or reflect, so that where the object's bounds lie changes
/// what they draw? Moving alone doesn't.
fn transform_measures(p: &serde_json::Value) -> bool {
p["scaleH"].as_f64() != Some(100.0)
|| p["scaleV"].as_f64() != Some(100.0)
|| p["rotate"].as_f64() != Some(0.0)
|| p["reflectX"].as_bool() != Some(false)
|| p["reflectY"].as_bool() != Some(false)
}
/// Do Free Distort params `p` move a corner of the box, so that where the object's bounds lie
/// changes what they draw?
fn free_distort_measures(p: &serde_json::Value) -> bool {
p["corners"] != serde_json::json!([[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]])
}
/// The largest Twist angle, in degrees either way, read as a live effect on an object that isn't a
@@ -1151,7 +1185,11 @@ const MAX_STRAIGHT_TWIST: f64 = 180.0;
/// compound path with straight segments (only at 0° when its guide members reach past its other
/// members, see [`guides_reach_past`]), or up to [`MAX_TWIST`] degrees either way on another object
/// with no guide in it. Transform that scales, turns or reflects is read only when nothing is stroked
/// (its reference point lies on the bounds without strokes).
/// (its reference point lies on the bounds without strokes) and, unless Transform Objects is off,
/// no guide reaches past the rest of the object's art ([`guides_reach_past`]). Free Distort that
/// moves a corner of a group is read only when no guide in the group reaches past the rest of its
/// art. The live effect is measured from bounds that take in the guides, so such an object keeps
/// its drawn look.
fn moves_with(object: &Node, st: &crate::import::ai::style::ArtStyle) -> bool {
use crate::import::ai::style::StyleItem;
let stroked = st.items.iter().any(|i| matches!(i, StyleItem::Stroke { paint, .. } if !paint.is_none()))
@@ -1171,12 +1209,14 @@ fn moves_with(object: &Node, st: &crate::import::ai::style::ArtStyle) -> bool {
}
"distort.transform" => {
let p = &e.params;
!stroked
|| (p["scaleH"].as_f64() == Some(100.0)
&& p["scaleV"].as_f64() == Some(100.0)
&& p["rotate"].as_f64() == Some(0.0)
&& p["reflectX"].as_bool() == Some(false)
&& p["reflectY"].as_bool() == Some(false))
// With Transform Objects off, nothing is placed from the bounds: a style read here and
// the object's members paint with no pattern for Transform Patterns to move (`simple`,
// `moves_alike`).
let placed = p["objects"].as_bool() != Some(false);
!transform_measures(p) || (!stroked && (!placed || !guides_reach_past(object)))
}
"distort.freeDistort" => {
!matches!(object.kind, NodeKind::Group { .. }) || !free_distort_measures(&e.params) || !guides_reach_past(object)
}
_ => true,
})
+86
View File
@@ -7551,6 +7551,92 @@ fn twist_is_read_on_straight_paths_and_compound_paths_up_to_half_a_turn() {
}
}
#[test]
fn transform_and_free_distort_keep_the_drawn_look_where_a_guide_reaches_past_the_rest_of_the_art() {
// GUARDS: a compound path or group whose guides reach past the rest of its art was read with a
// live Transform that scales, turns or reflects (or, on a group, a live Free Distort) measured from
// bounds that take in those guides. Such an object keeps its drawn look.
let hide = |s: String| s.replace('\n', "\n%_");
// A compound path of a square and `rest`, under its drawn look.
let compound = |rest: &str| {
format!(
"0 Ae\nu\n{RED}{}f\nU\n%_Bb\n%_{}0 BB\n1 (Bent) XW\n",
rect_path(16.0, 16.0, 64.0, 54.0),
hide(format!("*u\n{}f\n{rest}*U\n", rect_path(20.0, 20.0, 60.0, 50.0)))
)
};
// A group of a red square and `rest`, under its drawn look.
let group = |rest: &str| {
format!(
"0 Ae\nu\n{RED}{}f\nU\n%_0 Ae\n%_u\n%_{}U\n1 (Bent) XW\n",
rect_path(16.0, 16.0, 64.0, 54.0),
hide(format!("{RED}{}f\n{rest}", rect_path(20.0, 20.0, 60.0, 50.0)))
)
};
let guide = |from: (f64, f64), to: (f64, f64)| format!("{} {} m\n{} {} L\n(N) *\n", from.0, from.1, to.0, to.1);
let inside = guide((25.0, 25.0), (35.0, 35.0));
let past = guide((30.0, 30.0), (70.0, 40.0));
let nested = format!("0 Ae\nu\n{past}U\n");
let transform = |keys: &str| format!("{keys}0 /Bool (transformPatterns) ,\n");
let scale = transform("0.5 /Real (scaleH_Factor) ,\n0.5 /Real (scaleV_Factor) ,\n0 /Bool (scaleLines) ,\n");
let turn = transform("0.5 /Real (rotate_Radians) ,\n");
let reflect = transform("1 /Bool (reflectX) ,\n");
let moved = transform("5 /Real (moveH_Pts) ,\n");
let scale_in_place = transform("0.5 /Real (scaleH_Factor) ,\n0 /Bool (scaleLines) ,\n0 /Bool (transformObjects) ,\n");
// Transform Objects off and Transform Patterns on: only a pattern moves, and a solid fill has none.
let scale_patterns = "0.5 /Real (scaleH_Factor) ,\n0 /Bool (scaleLines) ,\n0 /Bool (transformObjects) ,\n1 /Bool (transformPatterns) ,\n";
let slanted = free_distort_keys([[25.0, 50.0], [65.0, 50.0], [20.0, 20.0], [60.0, 20.0]]);
let read = |name: &str, keys: &str, paint, art_: &str| read_ok(&format!("{}{}", distort_styles(name, keys, paint), layer(art_)));
let tr = "Adobe Transform";
let fd = "Adobe Free Distort";
for (what, r, id) in [
("a compound path scaled, its guide inside", read(tr, &scale, BLUE_FILL, &compound(&inside)), "distort.transform"),
("a compound path moved, its guide past", read(tr, &moved, BLUE_FILL, &compound(&past)), "distort.transform"),
("a compound path distorted, its guide past", read(fd, &slanted, BLUE_FILL, &compound(&past)), "distort.freeDistort"),
("a group scaled, its guide inside", read(tr, &scale, None, &group(&inside)), "distort.transform"),
("a group moved, its guide past", read(tr, &moved, None, &group(&past)), "distort.transform"),
("a group scaled with Transform Objects off, its guide past", read(tr, &scale_in_place, None, &group(&past)), "distort.transform"),
(
"a compound path scaled with Transform Objects off and Transform Patterns on, its guide past",
read(tr, scale_patterns, BLUE_FILL, &compound(&past)),
"distort.transform",
),
("a group distorted, its guide inside", read(fd, &slanted, None, &group(&inside)), "distort.freeDistort"),
("a group distorted with no corner moved, its guide past", read(fd, "", None, &group(&past)), "distort.freeDistort"),
// A hidden member is measured too, and this one takes in the guide.
(
"a group scaled, its guide past the square and inside a hidden member",
read(tr, &scale, None, &group(&format!("1 Xw\n{RED}{}f\n0 Xw\n{past}", rect_path(10.0, 10.0, 80.0, 60.0)))),
"distort.transform",
),
] {
assert!(!r.warnings.iter().any(|w| w.contains("drawn look")), "{what}: {:?}", r.warnings);
let a = art(&r.doc);
assert_eq!(a.len(), 1, "{what}: {a:#?}");
assert!(a[0].children().map_or(0, |c| c.len()) >= 2, "{what}: the object, not its look: {a:#?}");
let [e] = a[0].appearance.effects.as_slice() else { panic!("{what}: {:?}", a[0].appearance) };
assert_eq!(e.id, id, "{what}");
}
for (what, r) in [
("a compound path scaled, its guide past", read(tr, &scale, BLUE_FILL, &compound(&past))),
("a compound path turned, its guide past", read(tr, &turn, BLUE_FILL, &compound(&past))),
("a compound path reflected, its guide past", read(tr, &reflect, BLUE_FILL, &compound(&past))),
("a group scaled, its guide past", read(tr, &scale, None, &group(&past))),
("a group turned, its guide past", read(tr, &turn, None, &group(&past))),
("a group distorted, its guide past", read(fd, &slanted, None, &group(&past))),
("a group scaled, its guide past in a group in it", read(tr, &scale, None, &group(&nested))),
(
"a group scaled, its guide past in a compound path in it",
read(tr, &scale, None, &group(&format!("*u\n{RED}{}f\n{past}*U\n", rect_path(25.0, 25.0, 35.0, 35.0)))),
),
] {
let a = art(&r.doc);
assert_eq!(a.len(), 1, "{what}: {a:#?}");
assert!(a[0].appearance.effects.is_empty(), "{what}: the drawn look: {a:#?}");
assert!(r.warnings.iter().any(|w| w.contains("drawn look")), "{what}: {:?}", r.warnings);
}
}
#[test]
fn twist_on_a_straight_compound_path_keeps_the_drawn_look_where_a_guide_reaches_past_its_other_members() {
// GUARDS: a straight compound path whose guide members reach past its other members was read
+1
View File
@@ -122,6 +122,7 @@ const DIAMOND: &str = "diamond gradients are written as four linear gradients cl
const SPREAD: &str = "gradients that repeat or reflect are written with their stops repeated across the shape (legacy .ai gradients only pad)";
const SPREAD_CAPPED: &str = "gradients that repeat or reflect are written with at most 256 stops; they pad past those";
const HUE_STOPS: &str = "gradients mixed around the hue wheel are written in process colors, with the colors between their stops as stops of their own (at most 256; legacy .ai gradients mix their stops' colors directly)";
const PERCEPTUAL_STOPS: &str = "Perceptual gradients are written in process colors, with the colors between their stops as stops of their own (at most 256; legacy .ai gradients mix their stops' colors directly)";
/// Wedges a conic gradient is written as: one a degree.
const CONIC_WEDGES: usize = 360;
const STROKES: &str =
+132
View File
@@ -272,6 +272,81 @@ fn hue_wheel_gradients_are_written_with_the_stops_on_their_curve() {
}
}
/// The written definition of the gradient named `name` in `text`, and how many stops it holds.
fn definition<'a>(text: &'a str, name: &str) -> (&'a str, usize) {
let def = text.split(&format!("%AI5_BeginGradient: ({name})\n")).nth(1).and_then(|d| d.split("%AI5_EndGradient").next()).unwrap();
(def, def.matches(" %_Bs\n").count())
}
/// The format's gradients mix their stops' colors directly: a Perceptual gradient is written in
/// process colors with the colors on its curve as stops, no more than the reader reads, in a
/// definition of its own rather than its swatch's, with a warning, and opens with the colors it
/// had. A Classic gradient keeps its own stops and gives no warning.
#[test]
fn perceptual_gradients_are_written_with_the_stops_on_their_curve() {
use vectorcraft_color::{GradientMethod, Swatch};
let mut doc = Document::new(200.0, 100.0);
for (name, color) in [("Night", Color::cmyk(1.0, 1.0, 0.0, 0.0)), ("Sun", Color::cmyk(0.0, 0.0, 1.0, 0.0))] {
doc.swatches.push(Swatch { name: name.into(), paint: Paint::solid(color), global: true, spot: true });
}
let stop = |offset: f32, color: Color, swatch: &str| GradientStop { swatch: Some(swatch.into()), ..GradientStop::new(offset, color) };
let stops = vec![stop(0.0, Color::cmyk(1.0, 1.0, 0.0, 0.0), "Night"), stop(1.0, Color::cmyk(0.0, 0.0, 1.0, 0.0), "Sun")];
let mut g = GradientPaint::new(Gradient { method: GradientMethod::Perceptual, ..Gradient::new(GradientKind::Linear, stops) });
g.swatch = Some("Dusk".into());
let want = g.gradient.clone();
// The same stops mixed directly stray from the Perceptual curve, so a file holding only the
// two stops would not open with the colors it had.
let classic = Gradient { method: GradientMethod::Classic, ..want.clone() };
assert!(
(0..=100).any(|k| {
let t = k as f32 / 100.0;
want.sample(t).0.to_rgb().iter().zip(classic.sample(t).0.to_rgb()).any(|(a, b)| (a - b).abs() > 0.05)
}),
"the methods mix alike"
);
let n = shape(&mut doc, shapes::rectangle(Rect::new(20.0, 10.0, 180.0, 90.0)), Paint::Gradient(Box::new(g)), Paint::None);
let l = doc.layers[0].id;
doc.insert(Some(l), 0, n).unwrap();
let out = write(&doc);
assert!(out.warnings.iter().any(|w| w == PERCEPTUAL_STOPS), "{:?}", out.warnings);
assert!(!out.warnings.iter().any(|w| w == HUE_STOPS), "{:?}", out.warnings);
let text = String::from_utf8_lossy(&out.bytes).into_owned();
assert!(!text.contains("(Dusk)"), "the curve is not the swatch's gradient");
assert!(!text.contains("(Night)") && !text.contains("(Sun)"), "the stops are process colors: {text}");
let (_, written) = definition(&text, "Gradient");
assert!((3..=crate::import::MAX_GRADIENT_STOPS).contains(&written), "{written} stops");
let read = crate::import(&out.bytes).unwrap().document;
let mut back = None;
read.walk(|n| {
if let (None, Paint::Gradient(g)) = (&back, n.appearance.fill_paint()) {
back = Some(g.gradient.clone());
}
});
let back = back.unwrap();
assert!(back.method.is_classic());
assert_eq!(back.stops.len(), written, "every stop written is read");
assert!(back.stops.iter().all(|s| s.swatch.is_none()), "{:?}", back.stops);
for k in 0..=100 {
let t = k as f32 / 100.0;
let (a, b) = (want.sample(t).0.to_rgb(), back.sample(t).0.to_rgb());
assert!(a.iter().zip(b).all(|(x, y)| (x - y).abs() < 0.03), "at {t}: {a:?} vs {b:?}");
}
// Classic: its own two stops, its spot colors and its swatch's name, without the warning.
let mut doc = Document::new(200.0, 100.0);
doc.swatches.push(Swatch { name: "Night".into(), paint: Paint::solid(Color::cmyk(1.0, 1.0, 0.0, 0.0)), global: true, spot: true });
let mut g = GradientPaint::new(classic);
g.swatch = Some("Dusk".into());
let n = shape(&mut doc, shapes::rectangle(Rect::new(20.0, 10.0, 180.0, 90.0)), Paint::Gradient(Box::new(g)), Paint::None);
let l = doc.layers[0].id;
doc.insert(Some(l), 0, n).unwrap();
let out = write(&doc);
assert!(!out.warnings.iter().any(|w| w == PERCEPTUAL_STOPS), "{:?}", out.warnings);
let text = String::from_utf8_lossy(&out.bytes).into_owned();
assert_eq!(definition(&text, "Dusk").1, 2);
assert!(text.contains("%%DocumentCustomColors: (Night)"), "{text}");
}
/// A radial gradient repeated out from a center far from the shape is written with its ramp points
/// (percent) to five decimals, so its runs keep their places hundreds of runs out.
#[test]
@@ -1075,6 +1150,63 @@ fn rgb_stops_are_written_again_unchanged() {
assert_eq!(again, first);
}
/// With a working RGB space other than sRGB, a Lab fill and a freeform gradient's average color
/// are written as RGB values in the working RGB space, so they read back as RGB colors that show as
/// the colors they were written for.
#[test]
fn a_lab_fill_reads_back_as_the_same_color_in_a_wide_gamut_working_space() {
const CHILD: &str = "VECTORCRAFT_TEST_LEGACY_AI_WIDE_GAMUT_LAB";
if std::env::var_os(CHILD).is_none() {
// Color settings are process-wide: exercise this profile in a separate test process.
let output = std::process::Command::new(std::env::current_exe().unwrap())
.args(["--exact", "legacy_ai::tests::a_lab_fill_reads_back_as_the_same_color_in_a_wide_gamut_working_space", "--nocapture"])
.env(CHILD, "1")
.output()
.unwrap();
let stdout = String::from_utf8_lossy(&output.stdout);
assert!(
output.status.success() && stdout.contains("test result: ok. 1 passed; 0 failed;"),
"isolated color profile test failed:\n{stdout}\n{}",
String::from_utf8_lossy(&output.stderr),
);
return;
}
use vectorcraft_color::cms;
cms::set_active(&cms::ColorSettings { rgb: cms::WIDE_GAMUT_RGB.into(), ..Default::default() }).unwrap();
assert!(!cms::active().rgb_is_srgb());
let lab = Color::lab(60.0, 20.0, -30.0);
let mut doc = Document::new(100.0, 100.0);
let n = shape(&mut doc, shapes::rectangle(Rect::new(10.0, 10.0, 50.0, 50.0)), Paint::solid(lab), Paint::None);
let layer = doc.layers[0].id;
doc.insert(Some(layer), usize::MAX, n).unwrap();
// A freeform gradient is written as the average of its stops' display colors.
let (a, b) = (Color::rgb(0.9, 0.2, 0.1), Color::lab(50.0, -40.0, -20.0));
let stops = vec![GradientStop::new(0.0, a), GradientStop::new(1.0, b)];
let free = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Freeform, stops))));
let n = shape(&mut doc, shapes::rectangle(Rect::new(60.0, 10.0, 90.0, 50.0)), free, Paint::None);
doc.insert(Some(layer), usize::MAX, n).unwrap();
let average = {
let (a, b) = (a.to_rgb(), b.to_rgb());
[0, 1, 2].map(|i| (a[i] + b[i]) / 2.0)
};
// Written without [`write`]'s printed comparison, which paints a gradient in its first stop's
// color and not in the average color the writer writes for a freeform gradient.
let back = crate::import(&export_legacy_ai(&doc, &LegacyAiOptions::default()).unwrap().bytes).unwrap().document;
let mut read = vec![];
back.walk(|n| {
if let NodeKind::Path { .. } = n.kind {
read.push(n.appearance.fill_paint());
}
});
let [Paint::Solid { color: got @ Color::Rgb { .. }, .. }, Paint::Solid { color: avg @ Color::Rgb { .. }, .. }] = read.as_slice() else {
panic!("two RGB fills: {read:?}")
};
for (got, w, what) in [(got, lab.to_rgb(), "Lab fill"), (avg, average, "freeform gradient's average")] {
let g = got.to_rgb();
assert!(g.iter().zip(w).all(|(a, b)| (a - b).abs() < 2e-3), "{what} {got:?} shows as {g:?}, not {w:?}");
}
}
/// A gradient from white to #1b2a6b, the colors of #2687's circle, placed at `geom` (None: fitted
/// to the object).
fn white_to_navy(kind: GradientKind, geom: Option<vectorcraft_color::GradientGeom>) -> Paint {
+7 -10
View File
@@ -9,7 +9,7 @@ use super::{
ROTATED_TYPE, Rect, STROKES, SUBLAYERS, Shape, StrokeLayer, SubPath, TITLE_AND_COLOR_NAMES, TRANSPARENCY, TYPE, TYPE_ATTRIBUTES, TextKind,
TextObject, UNDECODED, Vec2, Write, ai_ops, latin, ps, stroke,
};
use super::{CONIC, CONIC_WEDGES, DIAMOND, GRAPHS, HUE_STOPS, SPREAD, SPREAD_CAPPED};
use super::{CONIC, CONIC_WEDGES, DIAMOND, GRAPHS, HUE_STOPS, PERCEPTUAL_STOPS, SPREAD, SPREAD_CAPPED};
#[cfg(test)]
thread_local! {
@@ -710,10 +710,7 @@ impl<'a> Writer<'a> {
Color::Cmyk { c, m, y, k } => Ink::Cmyk([c, m, y, k].map(unit)),
// The CMYK equivalent of the RGB values as written.
Color::Rgb { r, g, b } => Ink::Rgb(self.cms.to_cmyk(&ai_ops::as_written(*color), intent).map(unit), [r, g, b].map(unit)),
Color::Lab { .. } => {
let rgb = color.to_rgb().map(unit);
Ink::Rgb(self.cms.to_cmyk(color, intent).map(unit), rgb)
}
Color::Lab { .. } => Ink::Rgb(self.cms.to_cmyk(color, intent).map(unit), ai_ops::rgb_values(*color)),
}
}
@@ -755,11 +752,11 @@ impl<'a> Writer<'a> {
/// (its distance a fraction of the radius, at most 1, §3.5.5; `0 0 0 0 Bh` at the center,
/// §3.5.6), `1 (name) x y angle length 1 0 0 1 0 0 Bg`.
fn gradient(&mut self, g: &GradientPaint, bounds: Rect) -> String {
// A gradient mixed around the hue wheel (the format's gradients mix their stops' colors
// directly): the stops on its curve, no more than the reader reads, in a definition of
// its own.
if g.gradient.method.is_hue() {
self.warn(HUE_STOPS);
// A gradient mixed by the Perceptual method or around the hue wheel (the format's
// gradients mix their stops' colors directly): the stops on its curve, in process colors,
// no more than the reader reads, in a definition of its own.
if !g.gradient.method.is_classic() {
self.warn(if g.gradient.method.is_hue() { HUE_STOPS } else { PERCEPTUAL_STOPS });
let curve = g.gradient.as_classic_curve();
let gradient = if curve.is_spread() { curve } else { curve.fitted(crate::import::MAX_GRADIENT_STOPS).into_owned() };
let p = GradientPaint { gradient, swatch: None, ..g.clone() };
+10
View File
@@ -1569,6 +1569,16 @@ fn headless_backend_methods() {
assert_eq!(entry["label"], "Trim at Crossings Tool");
assert!(entry["shortcut"].is_null());
assert_eq!(h.call("ui.tool.select", json!({"tool": trim})).unwrap()["tool"], trim);
// The Enclosing Lasso Tool is listed once, in the Lasso tool's group after the Lasso.
let enclosing = vectorcraft_tools::addons::enclosing_lasso::ID;
let with_enclosing: Vec<_> =
groups.iter().map(|group| group.as_array().unwrap()).filter(|group| group.iter().any(|entry| entry["id"] == enclosing)).collect();
assert_eq!(with_enclosing.len(), 1, "{enclosing} is in one group");
let ids: Vec<_> = with_enclosing[0].iter().map(|entry| entry["id"].clone()).collect();
assert_eq!(ids, [json!("lasso"), json!(enclosing)]);
assert_eq!(with_enclosing[0][1]["label"], "Enclosing Lasso Tool");
assert!(with_enclosing[0][1]["shortcut"].is_null());
assert_eq!(h.call("ui.tool.select", json!({"tool": enclosing})).unwrap()["tool"], enclosing);
let polygonal = groups.iter().flat_map(|group| group.as_array().unwrap()).find(|entry| entry["id"] == "polygonalLasso");
assert_eq!(polygonal.map(|entry| entry["label"].clone()), Some(json!("Polygonal Lasso Tool")));
assert!(h.call("ui.resize", json!({})).is_err());
+74 -18
View File
@@ -46,12 +46,7 @@ use crate::{Imported, Kind};
const PATTERNS: &str = "hatched and pattern brushes are filled with their average color";
const ENDS_EARLY: &str = "the file ends early: what it held was imported";
const TOO_MANY: &str = "objects past the most one file may hold were left out";
const AT_LIMIT: &str = "the file reached the most objects one file may hold: any after them were not read";
/// The most items `craft_metafile` keeps from one file (its `MAX_ITEMS`). It stops reading at the
/// limit and does not say whether more items followed, so a picture holding this many may have
/// been cut short.
const READER_ITEMS: usize = 200_000;
const AT_LIMIT: &str = "the file or a picture inside it reached a limit on what one file may hold: what came after the limit was not read";
/// Points a unit of a WMF without a placeable header (1440 units an inch).
const WMF_UNIT: f64 = 72.0 / 1440.0;
@@ -217,6 +212,18 @@ struct Pending {
path: BezPath,
}
/// What `craft_metafile` counted as not read or not played as the file asks.
struct Lost {
/// Records of kinds it doesn't read.
skipped: u32,
/// Images, and pattern brushes (a pen's included), whose bitmap it couldn't read.
images: u32,
/// Clip changes it didn't apply as the file sets them.
clips: u32,
/// Raster operations drawn as a plain copy or left out.
rops: u32,
}
/// Clip paths already made, by address (the `Arc` keeps the address from being reused); None for
/// one that clips nothing in the picture.
type MadeClips = HashMap<*const ClipPath, (Arc<ClipPath>, Option<Arc<Clip>>)>;
@@ -561,10 +568,7 @@ impl Mapper {
let shape = if k > 1e-12 && k.is_finite() && linear.determinant().abs() > 1e-24 { Affine::scale(1.0 / k) * linear } else { Affine::IDENTITY };
let f = &t.font;
let h = f64::from(f.height);
// A negative height is the em; a positive one the cell (the em and the internal leading).
let em = if h < 0.0 { -h } else { h * 0.85 };
let size = if em > 0.0 && (em * k).is_finite() { (em * k).clamp(0.5, 5000.0) } else { 12.0 };
let mut style = CharStyle { size, fill: color(t.color), stroke: Paint::None, ..CharStyle::default() };
let mut style = CharStyle { fill: color(t.color), stroke: Paint::None, ..CharStyle::default() };
if !f.family.trim().is_empty() {
style.font_family = f.family.trim().to_string();
}
@@ -575,6 +579,33 @@ impl Mapper {
(false, false) => "Regular",
}
.into();
// The face the font maps to (the fallback face for a font that isn't installed). Characters
// it has no glyph for are drawn from other faces at the same size and Horizontal Scale.
let face = vectorcraft_text::FontDb::global().style_face(&style);
// A negative height is the em. A positive height is the character cell, and the em is
// the cell times unitsPerEm divided by the face's OS/2 usWinAscent plus usWinDescent at
// its instance of a variable font (its own ascent plus descent when it has no OS/2 table).
let cell_em = face.as_ref().and_then(|face| {
let (a, d) = face.vertical_metrics();
Some(face.units_per_em() / face.win_cell_height().unwrap_or(a + d)).filter(|r| r.is_finite() && *r > 0.0)
});
let em = if h < 0.0 { -h } else { h * cell_em.unwrap_or(0.85) };
let sized = em > 0.0 && (em * k).is_finite();
let size = if sized { (em * k).clamp(0.5, 5000.0) } else { 12.0 };
style.size = size;
// An average character width, negative or positive, becomes Horizontal Scale: the face's
// own average width (OS/2 xAvgCharWidth) at the type size is stretched or narrowed to it,
// also when the size was held to its range. A width is ignored when the height is 0.
let width = f64::from(f.width).abs();
if width > 0.0
&& sized
&& let Some(avg) = face.as_ref().and_then(|face| Some(face.average_char_width()? / face.units_per_em()))
{
let h_scale = width * k / (avg * size) * 100.0;
if h_scale.is_finite() {
style.h_scale = h_scale.clamp(1.0, 10000.0);
}
}
style.underline = f.underline;
style.strikethrough = f.strike;
let db = vectorcraft_text::FontDb::global();
@@ -696,14 +727,38 @@ impl Mapper {
}
/// The document: what was drawn on one layer, clipped art in clipping groups.
fn finish(mut self, kind: Kind, skipped: u32) -> Imported {
fn finish(mut self, kind: Kind, lost: Lost) -> Imported {
self.flush();
if skipped > 0 {
let n = skipped;
let s = |n: u32| if n == 1 { "" } else { "s" };
let was = |n: u32| if n == 1 { "was" } else { "were" };
let n = lost.skipped;
if n > 0 {
self.warnings.push(format!("{n} record{} of kinds VectorCraft doesn't read {} skipped", s(n), was(n)));
}
let n = lost.images;
if n > 0 {
self.warnings.push(format!(
"{n} record{} of kinds VectorCraft doesn't read {} skipped",
if n == 1 { "" } else { "s" },
if n == 1 { "was" } else { "were" }
"{n} image{} or pattern brush{} that couldn't be read {} left out",
s(n),
if n == 1 { "" } else { "es" },
was(n)
));
}
let n = lost.clips;
if n > 0 {
self.warnings.push(format!(
"{n} clip{} couldn't be applied as the file sets {}: what is drawn after {} may show more or less than the file does",
s(n),
if n == 1 { "it" } else { "them" },
if n == 1 { "it" } else { "them" }
));
}
let n = lost.rops;
if n > 0 {
self.warnings.push(format!(
"{n} raster operation{} other than a plain copy (masks, inversions) {} drawn as a plain copy or left out",
s(n),
was(n)
));
}
let out = std::mem::take(&mut self.out);
@@ -957,11 +1012,12 @@ pub(crate) fn import(bytes: &[u8]) -> Result<Imported, String> {
if ends_early(bytes, kind) {
m.warn(ENDS_EARLY);
}
if pic.items.len() >= READER_ITEMS {
if pic.truncated {
m.warn(AT_LIMIT);
}
let lost = Lost { skipped: pic.skipped_records, images: pic.dropped_images, clips: pic.ignored_clips, rops: pic.unplayed_raster_ops };
for item in pic.items {
m.item(item);
}
Ok(m.finish(kind, pic.skipped_records))
Ok(m.finish(kind, lost))
}
+2
View File
@@ -16,6 +16,8 @@
//! [`import`] reads either format (an EMF with its EMF+ records too, through `craft_metafile`)
//! into a document of one artboard (the picture's frame) and one layer: paths with fills and
//! strokes, clipping, images and text. Records it doesn't read are skipped, with one warning.
//! A picture cut short by a reader limit, images and pattern brushes that can't be read, clips
//! that can't be applied and raster operations other than a plain copy each add a warning.
//! [`import_pict`] reads QuickDraw pictures (PICT, versions 1 and 2) into the same kind of
//! document.
//!
+208 -1
View File
@@ -527,11 +527,100 @@ fn a_file_with_more_objects_than_are_read_says_so() {
let many = hand_emf(5000, 3000, &vec![rect.clone(); 200_010]);
let back = import(&many).unwrap();
assert_eq!(paths(&back.document).len(), 200_000);
assert!(back.warnings.iter().any(|w| w.contains("reached the most objects")), "{:?}", back.warnings);
assert!(back.warnings.iter().any(|w| w.contains("reached a limit")), "{:?}", back.warnings);
// Exactly as many as the reader keeps: nothing was left unread.
let full = import(&hand_emf(5000, 3000, &vec![rect.clone(); 200_000])).unwrap();
assert_eq!(paths(&full.document).len(), 200_000);
assert!(full.warnings.is_empty(), "{:?}", full.warnings);
let few = import(&hand_emf(5000, 3000, &vec![rect; 3])).unwrap();
assert!(few.warnings.is_empty(), "{:?}", few.warnings);
}
#[test]
fn a_file_cut_short_by_another_limit_says_so() {
// SAVEDC past the 1,024 levels the reader keeps stops the parse: the rectangle after them is
// not read.
let mut records = vec![(43, le(&[0, 0, 100, 100]))];
records.extend(vec![(33, vec![]); 1100]);
records.push((43, le(&[200, 200, 300, 300])));
let back = import(&hand_emf(5000, 3000, &records)).unwrap();
assert_eq!(paths(&back.document).len(), 1);
assert_eq!(
back.warnings,
vec!["the file or a picture inside it reached a limit on what one file may hold: what came after the limit was not read".to_string()]
);
}
#[test]
fn images_the_reader_does_not_read_are_counted() {
let records = vec![(81, png_stretch_dibits(&png_claiming(1 << 13, 1 << 13))); 2];
let back = import(&hand_emf(5000, 3000, &records)).unwrap();
assert_eq!(back.warnings, vec!["2 images or pattern brushes that couldn't be read were left out".to_string()]);
let back = import(&hand_emf(5000, 3000, &records[..1])).unwrap();
assert_eq!(back.warnings, vec!["1 image or pattern brush that couldn't be read was left out".to_string()]);
}
#[test]
fn a_wmf_reports_unread_pattern_brushes_and_raster_operations() {
let records = vec![
// DIBCREATEPATTERNBRUSH (style 5, usage 0) whose bitmap header can't be read.
(0x0142, [le16(&[5, 0]), vec![0xFF; 8]].concat()),
// A bitmap-less DIBBITBLT with DSTINVERT (0x00550009): rop, ySrc, xSrc, reserved, height,
// width, yDest, xDest.
(0x0940, le16(&[0x0009, 0x0055, 0, 0, 0, 100, 100, 0, 0])),
];
let back = import(&hand_wmf(1440, 1440, &records)).unwrap();
assert_eq!(
back.warnings,
vec![
"1 image or pattern brush that couldn't be read was left out".to_string(),
"1 raster operation other than a plain copy (masks, inversions) was drawn as a plain copy or left out".to_string(),
]
);
}
#[test]
fn clips_that_are_not_applied_are_counted() {
// BEGINPATH, a rectangle, ENDPATH, SELECTCLIPPATH with RGN_XOR (3), then a rectangle drawn after it.
let records = vec![(59, vec![]), (43, le(&[100, 100, 2000, 2000])), (60, vec![]), (67, le(&[3])), (43, le(&[500, 500, 600, 600]))];
let back = import(&hand_emf(5000, 3000, &records)).unwrap();
assert_eq!(paths(&back.document).len(), 1);
assert_eq!(
back.warnings,
vec!["1 clip couldn't be applied as the file sets it: what is drawn after it may show more or less than the file does".to_string()]
);
// RGN_AND (1) is applied.
let mut records = records;
records[3] = (67, le(&[1]));
let back = import(&hand_emf(5000, 3000, &records)).unwrap();
assert!(back.warnings.is_empty(), "{:?}", back.warnings);
}
/// An EMR_BITBLT of the 100 × 100 box at the origin with `rop` and no source bitmap.
fn bitblt(rop: u32) -> Vec<u8> {
// Bounds; destination; the operation; the source origin, transform (identity) and background
// color; usage, then no BITMAPINFO and no bits.
let mut body = vec![0; 16];
body.extend(le(&[0, 0, 100, 100, rop as i32, 0, 0]));
body.extend(le_f32(&[1.0, 0.0, 0.0, 1.0, 0.0, 0.0]));
body.extend(le(&[0, 0, 0, 0, 0, 0]));
body
}
#[test]
fn raster_operations_that_are_not_played_are_counted() {
// DSTINVERT and PATINVERT take no source bitmap and are left out.
let records = vec![(76, bitblt(0x0055_0009)), (76, bitblt(0x005A_0049))];
let back = import(&hand_emf(5000, 3000, &records)).unwrap();
assert_eq!(
back.warnings,
vec!["2 raster operations other than a plain copy (masks, inversions) were drawn as a plain copy or left out".to_string()]
);
// WHITENESS is played.
let back = import(&hand_emf(5000, 3000, &[(76, bitblt(0x00FF_0062))])).unwrap();
assert!(back.warnings.is_empty(), "{:?}", back.warnings);
}
/// An EMR_STRETCHDIBITS copying `png` (a BI_PNG bitmap) to a 10 × 10 box.
fn png_stretch_dibits(png: &[u8]) -> Vec<u8> {
// Bounds; destination, source and its size; the BITMAPINFO and the bits (from the record start);
@@ -677,6 +766,124 @@ fn text_keeps_a_stretch_across() {
assert!((a - 2.0).abs() < 1e-6 && b.abs() < 1e-6 && c.abs() < 1e-6 && (d - 1.0).abs() < 1e-6, "{:?}", t.xf);
}
/// Source Sans 3 Regular's own values, read from its table directory: unitsPerEm (`head`),
/// xAvgCharWidth and usWinAscent + usWinDescent (`OS/2`), in font units.
fn source_sans_metrics() -> (f64, f64, f64) {
let font: &[u8] = include_bytes!("../../../../assets/fonts/SourceSans3-Regular.ttf");
let u16_at = |at: usize| u16::from_be_bytes([font[at], font[at + 1]]);
let table = |tag: &[u8; 4]| {
let at = (0..usize::from(u16_at(4))).map(|i| 12 + 16 * i).find(|at| &font[*at..*at + 4] == tag).unwrap();
u32::from_be_bytes([font[at + 8], font[at + 9], font[at + 10], font[at + 11]]) as usize
};
let (head, os2) = (table(b"head"), table(b"OS/2"));
let avg = f64::from(i16::from_be_bytes([font[os2 + 2], font[os2 + 3]]));
(f64::from(u16_at(head + 18)), avg, f64::from(u16_at(os2 + 74)) + f64::from(u16_at(os2 + 76)))
}
/// The style of "Hi" drawn in an EMF in Source Sans 3 with a LOGFONT of `height` and `width`
/// (hundredths of a millimeter).
fn emf_font_style(height: i32, width: i32) -> vectorcraft_doc::CharStyle {
emf_font_style_in("Source Sans 3", height, width)
}
/// [`emf_font_style`] with the LOGFONT naming `family`.
fn emf_font_style_in(family: &str, height: i32, width: i32) -> vectorcraft_doc::CharStyle {
let mut text = vec![0; 16];
text.extend(le(&[1, 0, 0]));
text.extend(le(&[1000, 1500, 2, 76, 0, 0, 0, 0, 0, 0]));
text.extend("Hi".encode_utf16().flat_map(u16::to_le_bytes));
let mut font = le(&[2, height, width, 0, 0, 400]);
font.extend([0u8; 8]);
font.extend(family.encode_utf16().chain(std::iter::repeat_n(0, 32 - family.encode_utf16().count())).flat_map(u16::to_le_bytes));
let records = vec![(82, font), (37, le(&[2])), (84, text)];
let back = import(&hand_emf(5000, 3000, &records)).unwrap();
let t = all(&back.document)
.into_iter()
.find_map(|n| match n.kind {
NodeKind::Text(t) => Some(t),
_ => None,
})
.unwrap();
t.runs[0].style.clone()
}
#[test]
fn a_font_width_becomes_horizontal_scale() {
let (upem, avg, _) = source_sans_metrics();
let mm = 72.0 / 25.4;
// A 10 mm em and an average character width of 6 mm: the face's average width, avg/upem of
// the em, is scaled to 6 mm.
let want = 6.0 / (avg / upem * 10.0) * 100.0;
for width in [600, -600] {
let st = emf_font_style(-1000, width);
assert_eq!(st.font_family, "Source Sans 3");
assert!((st.size - 10.0 * mm).abs() < 1e-9, "{}", st.size);
assert!((st.h_scale - want).abs() < 1e-9, "width {width}: {} for {want}", st.h_scale);
}
assert_eq!(emf_font_style(-1000, 0).h_scale, 100.0);
// A 4 m em is set at the largest type size, 5000 pt, and a 2.4 m average width keeps its
// width at that size.
let st = emf_font_style(-400_000, 240_000);
assert_eq!(st.size, 5000.0);
let want = 2400.0 * mm / (avg / upem * 5000.0) * 100.0;
assert!((st.h_scale - want).abs() < 1e-9, "{} for {want}", st.h_scale);
// With a height of 0 the type is set at the default size and the width is ignored.
assert_eq!(emf_font_style(0, 600).h_scale, 100.0);
}
#[test]
fn a_positive_font_height_is_the_character_cell() {
let (upem, avg, cell) = source_sans_metrics();
let mm = 72.0 / 25.4;
// A 10 mm cell: the em is the cell times unitsPerEm divided by the face's usWinAscent plus
// usWinDescent, and a 6 mm average width is measured against that em.
let em = 10.0 * upem / cell;
let st = emf_font_style(1000, 600);
assert!((st.size - em * mm).abs() < 1e-9, "{} for {}", st.size, em * mm);
let want = 6.0 / (avg / upem * em) * 100.0;
assert!((st.h_scale - want).abs() < 1e-9, "{} for {want}", st.h_scale);
}
#[test]
fn a_font_the_system_lacks_is_measured_in_the_face_that_draws_it() {
// A family no system has keeps its name, and layout draws it in Source Sans 3: the cell and
// the average width are measured in that face.
let (upem, avg, cell) = source_sans_metrics();
let mm = 72.0 / 25.4;
let st = emf_font_style_in("Missing Family 7183", 1000, 600);
assert_eq!(st.font_family, "Missing Family 7183");
let em = 10.0 * upem / cell;
assert!((st.size - em * mm).abs() < 1e-9, "{} for {}", st.size, em * mm);
let want = 6.0 / (avg / upem * em) * 100.0;
assert!((st.h_scale - want).abs() < 1e-9, "{} for {want}", st.h_scale);
}
#[test]
fn wmf_font_width_becomes_horizontal_scale() {
let (upem, avg, _) = source_sans_metrics();
// CREATEFONTINDIRECT: a 0.1 inch em (144 units) with an average width of 72 units, then
// SELECTOBJECT and TEXTOUT "Hi" at (720, 360).
let mut font = le16(&[-144, 72, 0, 0, 400]);
font.extend([0u8; 8]);
font.extend(b"Source Sans 3".iter().copied().chain(std::iter::repeat_n(0, 19)));
let mut text = le16(&[2]);
text.extend(b"Hi");
text.extend(le16(&[360, 720]));
let records = vec![(0x02FB, font), (0x012D, le16(&[0])), (0x0521, text)];
let back = import(&hand_wmf(1440, 1440, &records)).unwrap();
let t = all(&back.document)
.into_iter()
.find_map(|n| match n.kind {
NodeKind::Text(t) => Some(t),
_ => None,
})
.unwrap();
let st = &t.runs[0].style;
assert!((st.size - 7.2).abs() < 1e-9, "{}", st.size);
let want = 72.0 / (avg / upem * 144.0) * 100.0;
assert!((st.h_scale - want).abs() < 1e-9, "{} for {want}", st.h_scale);
}
#[test]
fn a_clip_whose_box_holds_the_picture_still_clips() {
// A diamond around the middle of the picture, whose box holds the whole frame but which cuts
@@ -34,9 +34,19 @@ fn flat(c: &CubicBez) -> bool {
off(c.p1) <= FLAT && off(c.p2) <= FLAT
}
/// Where the chords of `a` and `b` cross: (s, u) along each, or `None` when they don't (parallel
/// ones never do).
fn chords_cross(a: &CubicBez, b: &CubicBez) -> Option<(f64, f64)> {
/// Which ends of a segment are open ends of its path: (start, end).
type Open = (bool, bool);
/// The open ends of segment `s` of `sp`.
fn open_ends(sp: &SubPath, s: usize) -> Open {
(!sp.closed && s == 0, !sp.closed && s + 1 == sp.segment_count())
}
/// Where the straight pieces `a` and `b` cross: (t on `a`, t on `b`), or `None` when their chords
/// don't cross (parallel ones never do, so paths lying along each other don't cross). An end in
/// `open_a` or `open_b` (start, end) that lies within [`SAME`] of the other piece meets it at the
/// point of that piece nearest it, at any angle.
fn pieces_cross(a: &CubicBez, b: &CubicBez, open_a: Open, open_b: Open) -> Option<(f64, f64)> {
let (da, db) = (a.p3 - a.p0, b.p3 - b.p0);
let den = da.cross(db);
if den.abs() <= 1e-12 * da.hypot() * db.hypot() || den == 0.0 {
@@ -45,7 +55,20 @@ fn chords_cross(a: &CubicBez, b: &CubicBez) -> Option<(f64, f64)> {
let w = b.p0 - a.p0;
let (s, u) = (w.cross(db) / den, w.cross(da) / den);
let within = |v: f64| (-1e-9..=1.0 + 1e-9).contains(&v);
(within(s) && within(u)).then(|| (s.clamp(0.0, 1.0), u.clamp(0.0, 1.0)))
if within(s) && within(u) {
// The pieces are straight but their parameters needn't run evenly along them.
let (s, u) = (s.clamp(0.0, 1.0), u.clamp(0.0, 1.0));
return Some((a.nearest(a.p0.lerp(a.p3, s), 1e-9).t, b.nearest(b.p0.lerp(b.p3, u), 1e-9).t));
}
let ends_a = [(open_a.0, 0.0, a.p0), (open_a.1, 1.0, a.p3)].into_iter().filter(|e| e.0).map(|(_, ta, p)| {
let n = b.nearest(p, 1e-9);
((ta, n.t), n.distance_sq)
});
let ends_b = [(open_b.0, 0.0, b.p0), (open_b.1, 1.0, b.p3)].into_iter().filter(|e| e.0).map(|(_, tb, p)| {
let n = a.nearest(p, 1e-9);
((n.t, tb), n.distance_sq)
});
ends_a.chain(ends_b).filter(|e| e.1 < SAME * SAME).min_by(|x, y| x.1.total_cmp(&y.1)).map(|e| e.0)
}
/// `(s, t)` moved to where `a` and `b` cross exactly, by Newton's method on a(s) = b(t), or as it
@@ -85,8 +108,11 @@ fn refined(a: &CubicBez, b: &CubicBez, (s0, t0): (f64, f64)) -> (f64, f64) {
}
/// Where segments `a` and `b` cross: (t on `a`, t on `b`) pairs, halving both while their control
/// boxes meet until each piece is straight. `None` once `budget` steps are spent.
fn segment_crossings(a: &CubicBez, b: &CubicBez, budget: &mut usize) -> Option<Vec<(f64, f64)>> {
/// boxes meet until each piece is straight. `None` once `budget` steps are spent. `open_a` and
/// `open_b` are the segments' ends that are open ends of their paths (start, end): such an end
/// within [`SAME`] of the other segment meets it there, as a path cut where another crosses it
/// ends a little off that path.
fn segment_crossings(a: &CubicBez, b: &CubicBez, open_a: Open, open_b: Open, budget: &mut usize) -> Option<Vec<(f64, f64)>> {
let mut stack = vec![(0.0, 1.0, 0.0, 1.0, 0u32)];
let mut found: Vec<(f64, f64)> = vec![];
while let Some((a0, a1, b0, b1, depth)) = stack.pop() {
@@ -96,10 +122,9 @@ fn segment_crossings(a: &CubicBez, b: &CubicBez, budget: &mut usize) -> Option<V
continue;
}
if (flat(&ca) && flat(&cb)) || depth >= MAX_DEPTH {
if let Some((s, u)) = chords_cross(&ca, &cb) {
// The pieces are straight but their parameters needn't run evenly along them.
let x = ca.p0.lerp(ca.p3, s);
let (ta, tb) = (ca.nearest(x, 1e-9).t, cb.nearest(cb.p0.lerp(cb.p3, u), 1e-9).t);
// Only a piece's ends that are the segment's open ends reach past it.
let (oa, ob) = ((open_a.0 && a0 == 0.0, open_a.1 && a1 == 1.0), (open_b.0 && b0 == 0.0, open_b.1 && b1 == 1.0));
if let Some((ta, tb)) = pieces_cross(&ca, &cb, oa, ob) {
found.push((a0 + ta * (a1 - a0), b0 + tb * (b1 - b0)));
}
continue;
@@ -193,18 +218,21 @@ fn shared_anchors(sp: &SubPath, with_length: &[usize], i: usize, j: usize) -> Ve
/// Where segments `a` and `b` cross, without the places at the anchors in `shared`: two segments that
/// meet at an anchor don't cross there, but they can cross again elsewhere.
fn crossings_apart(a: &CubicBez, b: &CubicBez, shared: &[Point], budget: &mut usize) -> Option<Vec<(f64, f64)>> {
let mut found = segment_crossings(a, b, budget)?;
fn crossings_apart(a: (&CubicBez, Open), b: (&CubicBez, Open), shared: &[Point], budget: &mut usize) -> Option<Vec<(f64, f64)>> {
let ((a, open_a), (b, open_b)) = (a, b);
let mut found = segment_crossings(a, b, open_a, open_b, budget)?;
found.retain(|(ta, _)| !shared.iter().any(|p| a.eval(*ta).distance(*p) < SAME));
Some(found)
}
/// Where `paths` cross one another (and, with `self_crossings`, where each crosses itself, a segment
/// that loops over itself included): for each path, the places on it, in order. Segments that meet
/// at an anchor they share don't count as crossing there. `None` past [`MAX_CROSSING_SEGMENTS`]
/// segments or when the curves are too tangled to sort out, or when a coordinate isn't finite.
/// at an anchor they share don't count as crossing there, and an open end of a path that lies
/// within 0.001 pt of another path (or of itself) meets it there; paths that lie along each other
/// don't cross. `None` past [`MAX_CROSSING_SEGMENTS`] segments or when the curves are too tangled
/// to sort out, or when a coordinate isn't finite.
pub fn crossings(paths: &[&PathData], self_crossings: bool) -> Option<Vec<Vec<Place>>> {
let mut segs: Vec<(usize, usize, usize, CubicBez, Rect)> = vec![];
let mut segs: Vec<(usize, usize, usize, CubicBez, Rect, Open)> = vec![];
for (k, path) in paths.iter().enumerate() {
for (si, sp) in path.subpaths.iter().enumerate() {
for s in 0..sp.segment_count() {
@@ -212,7 +240,7 @@ pub fn crossings(paths: &[&PathData], self_crossings: bool) -> Option<Vec<Vec<Pl
if ![c.p0, c.p1, c.p2, c.p3].iter().all(|p| p.x.is_finite() && p.y.is_finite()) {
return None;
}
segs.push((k, si, s, c, control_box(&c)));
segs.push((k, si, s, c, control_box(&c), open_ends(sp, s)));
if segs.len() > MAX_CROSSING_SEGMENTS {
return None;
}
@@ -222,11 +250,11 @@ pub fn crossings(paths: &[&PathData], self_crossings: bool) -> Option<Vec<Vec<Pl
let with_length: Vec<Vec<Vec<usize>>> = paths.iter().map(|p| p.subpaths.iter().map(with_length_from).collect()).collect();
let mut out: Vec<Vec<Place>> = vec![vec![]; paths.len()];
let mut budget = MAX_STEPS;
for (i, (ka, sa, ia, ca, ra)) in segs.iter().enumerate() {
for (i, (ka, sa, ia, ca, ra, oa)) in segs.iter().enumerate() {
if self_crossings && let Some((s, t)) = self_crossing(ca) {
out.get_mut(*ka)?.extend([(*sa, *ia, s), (*sa, *ia, t)]);
}
for (kb, sb, ib, cb, rb) in segs.iter().skip(i + 1) {
for (kb, sb, ib, cb, rb, ob) in segs.iter().skip(i + 1) {
if (ka == kb && !self_crossings) || !ra.inflate(SAME, SAME).overlaps(*rb) {
continue;
}
@@ -234,7 +262,7 @@ pub fn crossings(paths: &[&PathData], self_crossings: bool) -> Option<Vec<Vec<Pl
(Some(sp), Some(w)) if ka == kb && sa == sb => shared_anchors(sp, w, *ia, *ib),
_ => vec![],
};
for (ta, tb) in crossings_apart(ca, cb, &shared, &mut budget)? {
for (ta, tb) in crossings_apart((ca, *oa), (cb, *ob), &shared, &mut budget)? {
out.get_mut(*ka)?.push((*sa, *ia, ta));
out.get_mut(*kb)?.push((*sb, *ib, tb));
}
@@ -289,41 +317,43 @@ impl Work {
}
/// Where `others` cross `path`, and where `path` crosses itself (a segment that loops over itself
/// included): the places on `path`, in order, within the work of [`Work::default`].
/// included): the places on `path`, in order, within the work of [`Work::default`]. An open end of
/// a path that lies within 0.001 pt of another meets it there, as [`crossings_on_within`] says.
pub fn crossings_on(path: &PathData, others: &[&PathData]) -> Option<Vec<Place>> {
crossings_on_within(path, others, &mut Work::default())
}
/// [`crossings_on`], drawing on `work`. Only the segments of `others` whose control boxes meet the
/// box of `path` are compared with it, so the paths far from it cost one box test per segment.
/// Segments of `path` that meet at an anchor they share don't count as crossing there, and a
/// segment of `others` with a coordinate that isn't finite is left out. `None` when `path` has more
/// than [`MAX_CROSSING_SEGMENTS`] segments or a coordinate that isn't finite, when more than
/// Segments of `path` that meet at an anchor they share don't count as crossing there, an open end
/// of a path that lies within 0.001 pt of another meets it there, and a segment of `others` with a
/// coordinate that isn't finite is left out. `None` when `path` has more than
/// [`MAX_CROSSING_SEGMENTS`] segments or a coordinate that isn't finite, when more than
/// [`MAX_CROSSED_BY_SEGMENTS`] segments of `others` lie in its box, when the pairs of segments to
/// look at are more than `work` has left, or when the curves are too tangled to sort out in the
/// steps it has left.
pub fn crossings_on_within(path: &PathData, others: &[&PathData], work: &mut Work) -> Option<Vec<Place>> {
let mut own: Vec<(usize, usize, CubicBez, Rect)> = vec![];
let mut own: Vec<(usize, usize, CubicBez, Rect, Open)> = vec![];
for (si, sp) in path.subpaths.iter().enumerate() {
for s in 0..sp.segment_count() {
let c = sp.segment(s);
if ![c.p0, c.p1, c.p2, c.p3].iter().all(|p| p.x.is_finite() && p.y.is_finite()) {
return None;
}
own.push((si, s, c, control_box(&c)));
own.push((si, s, c, control_box(&c), open_ends(sp, s)));
if own.len() > MAX_CROSSING_SEGMENTS {
return None;
}
}
}
let Some(reach) = own.iter().map(|o| o.3).reduce(|a, b| a.union(b)).map(|r| r.inflate(SAME, SAME)) else { return Some(vec![]) };
let mut near: Vec<(CubicBez, Rect)> = vec![];
let mut near: Vec<(CubicBez, Rect, Open)> = vec![];
for sp in others.iter().flat_map(|p| &p.subpaths) {
for s in 0..sp.segment_count() {
let c = sp.segment(s);
let r = control_box(&c);
if [c.p0, c.p1, c.p2, c.p3].iter().all(|p| p.x.is_finite() && p.y.is_finite()) && reach.overlaps(r) {
near.push((c, r));
near.push((c, r, open_ends(sp, s)));
if near.len() > MAX_CROSSED_BY_SEGMENTS {
return None;
}
@@ -334,17 +364,17 @@ pub fn crossings_on_within(path: &PathData, others: &[&PathData], work: &mut Wor
let with_length: Vec<Vec<usize>> = path.subpaths.iter().map(with_length_from).collect();
let mut out: Vec<Place> = vec![];
let budget = &mut work.steps;
for (i, (sa, ia, ca, ra)) in own.iter().enumerate() {
for (i, (sa, ia, ca, ra, oa)) in own.iter().enumerate() {
let ra = ra.inflate(SAME, SAME);
if let Some((s, t)) = self_crossing(ca) {
out.extend([(*sa, *ia, s), (*sa, *ia, t)]);
}
for (cb, rb) in &near {
for (cb, rb, ob) in &near {
if ra.overlaps(*rb) {
out.extend(segment_crossings(ca, cb, budget)?.into_iter().map(|(ta, _)| (*sa, *ia, ta)));
out.extend(segment_crossings(ca, cb, *oa, *ob, budget)?.into_iter().map(|(ta, _)| (*sa, *ia, ta)));
}
}
for (sb, ib, cb, rb) in own.iter().skip(i + 1) {
for (sb, ib, cb, rb, ob) in own.iter().skip(i + 1) {
if !ra.overlaps(*rb) {
continue;
}
@@ -352,7 +382,7 @@ pub fn crossings_on_within(path: &PathData, others: &[&PathData], work: &mut Wor
(Some(sp), Some(w)) if sa == sb => shared_anchors(sp, w, *ia, *ib),
_ => vec![],
};
for (ta, tb) in crossings_apart(ca, cb, &shared, budget)? {
for (ta, tb) in crossings_apart((ca, *oa), (cb, *ob), &shared, budget)? {
out.push((*sa, *ia, ta));
out.push((*sb, *ib, tb));
}
@@ -725,3 +725,58 @@ fn a_slice_of_a_curve_keeps_its_shape_and_the_anchors_it_runs_through() {
assert!(slice(&circle, (2.0, 1.0)).anchors.is_empty());
assert!(slice(&circle, (f64::NAN, 1.0)).anchors.is_empty());
}
#[test]
fn an_open_end_a_hair_off_another_path_still_meets_it() {
// A bow from (0, 0) to (100, 100), and where a line across at y = 50 crosses it.
let bow = PathData::single(SubPath::new(
vec![Anchor { h_out: pt(0.0, 55.0), ..Anchor::corner(pt(0.0, 0.0)) }, Anchor { h_in: pt(45.0, 100.0), ..Anchor::corner(pt(100.0, 100.0)) }],
false,
));
let across = PathData::single(line(&[(-50.0, 50.0), (150.0, 50.0)], false));
let at = crossings_on(&across, &[&bow]).unwrap();
assert_eq!(at.len(), 1);
let p = across.subpaths[0].segment(0).eval(at[0].2);
// A line ending 0.00005 pt short of the bow, or past it, as a line cut where the bow crosses it
// can: the bow is crossed there, on both searches.
let on_bow = |l: &PathData| crossings_on(&bow, &[l]).unwrap().iter().map(|q| bow.subpaths[0].segment(q.1).eval(q.2)).collect::<Vec<_>>();
for off in [-5e-5, 5e-5] {
let stub = PathData::single(line(&[(-50.0, 50.0), (p.x + off, 50.0)], false));
let found = on_bow(&stub);
assert!(found.len() == 1 && found[0].distance(p) < 1e-3, "{off}: {found:?}");
let both = crossings(&[&stub, &bow], false).unwrap();
assert_eq!((both[0].len(), both[1].len()), (1, 1), "{off}: {both:?}");
}
// 0.01 pt short is not on it.
assert!(on_bow(&PathData::single(line(&[(-50.0, 50.0), (p.x - 0.01, 50.0)], false))).is_empty());
// The bow's own open end 0.00005 pt short of an upright meets it there.
let upright = PathData::single(line(&[(100.00005, 50.0), (100.00005, 150.0)], false));
let found = crossings_on(&upright, &[&bow]).unwrap();
assert!(found.len() == 1 && near(upright.subpaths[0].segment(0).eval(found[0].2).y, 100.0, 1e-3), "{found:?}");
// Two ends that each stop 0.0009 pt short of a corner lie 0.0013 pt apart: they don't meet.
let flat = PathData::single(line(&[(0.0, 0.0), (99.9991, 0.0)], false));
let post = PathData::single(line(&[(100.0, 0.0009), (100.0, 50.0)], false));
assert!(crossings_on(&flat, &[&post]).unwrap().is_empty() && crossings_on(&post, &[&flat]).unwrap().is_empty());
// Two ends that each stop 0.0004 pt short of a corner lie 0.0006 pt apart: they meet.
let flat = PathData::single(line(&[(0.0, 0.0), (99.9996, 0.0)], false));
let post = PathData::single(line(&[(100.0, 0.0004), (100.0, 50.0)], false));
assert_eq!((crossings_on(&flat, &[&post]).unwrap().len(), crossings_on(&post, &[&flat]).unwrap().len()), (1, 1));
// A level line that crosses a quarter circle near its top, where the two meet at under 3
// degrees, cut 0.0015 pt short along its length: its end lies under 0.0001 pt from the arc and
// meets it there.
use kurbo::ParamCurveNearest;
let arc = PathData::single(quarter());
let level = PathData::single(line(&[(50.0, 99.9), (-50.0, 99.9)], false));
let at = crossings_on(&level, &[&arc]).unwrap();
assert_eq!(at.len(), 1);
let end = level.subpaths[0].segment(0).eval(at[0].2) + Vec2::new(0.0015, 0.0);
assert!(arc.subpaths[0].segment(0).nearest(end, 1e-12).distance_sq.sqrt() < 1e-4);
let stub = PathData::single(line(&[(50.0, 99.9), (end.x, end.y)], false));
let found = crossings_on(&arc, &[&stub]).unwrap();
assert!(found.len() == 1 && arc.subpaths[0].segment(0).eval(found[0].2).distance(end) < 1e-3, "{found:?}");
assert_eq!(crossings(&[&stub, &arc], false).unwrap().iter().map(Vec::len).collect::<Vec<_>>(), [1, 1]);
// A corner of a closed path as near a line is not an open end: it doesn't reach the line.
let wedge = PathData::single(line(&[(180.0, 0.0), (220.0, 0.0), (200.0, 49.99995)], true));
let floor = PathData::single(line(&[(150.0, 50.0), (250.0, 50.0)], false));
assert!(crossings_on(&floor, &[&wedge]).unwrap().is_empty() && crossings_on(&wedge, &[&floor]).unwrap().is_empty());
}
+2
View File
@@ -54,6 +54,8 @@ vectorcraft-text = { workspace = true, features = ["test-fonts"] }
serde_json = { workspace = true }
# `draw_text`, to write test files with live text as other writers do.
krilla = { workspace = true, features = ["simple-text"] }
# How many times the symbol list is read to find symbols by name.
vectorcraft-doc = { workspace = true, features = ["symbol-read-count"] }
# An independent raster oracle for gradient placement in PDF forms. These are test-only macOS
# bindings; the exporter stays portable Rust and does not depend on an OS PDF renderer.
+18 -15
View File
@@ -118,7 +118,7 @@ impl Exporter<'_> {
if several && !elements.iter().skip(1).all(|(c, _)| shape_is_coverage(c)) {
let doc = self.doc;
let brushes = self.brushes.get_or_insert_with(|| vectorcraft_brush::library(doc));
match knockout_masks(BrushSearch::new(doc, brushes), &elements) {
match knockout_masks(BrushSearch::new(&self.symbols, brushes), &elements) {
Ok(above) => {
// Every mask is made before anything is drawn: when the symbol objects the
// masks may hold run out, one would leave out art its element covers, and
@@ -452,7 +452,7 @@ impl Exporter<'_> {
// A dynamic symbol's instance shows its own appearance changes, and the instance's
// fill stains its art, as on the canvas.
let doc = self.doc;
if let Some(sym) = doc.symbols.iter().find(|x| &x.name == symbol) {
if let Some(sym) = self.symbols.symbol(symbol) {
let changed;
let art: &Node = if n.extras().symbol_overrides.is_empty() && vectorcraft_doc::symbol_overrides::stain(n).is_none() {
&sym.art
@@ -968,8 +968,10 @@ enum SharedArt {
/// A search for the brushed strokes drawing an object draws, whose brush art can hold many more
/// objects than the stroked path.
struct BrushSearch<'a> {
doc: &'a Document,
struct BrushSearch<'a, 'd> {
doc: &'d Document,
/// `doc`'s symbols, found by name.
symbols: &'a vectorcraft_doc::SymbolBoxes<'d>,
/// The brushes the export draws strokes with ([`Exporter::brush_art`]); a stroke whose brush
/// is not among them is drawn as a plain stroke.
brushes: &'a [vectorcraft_brush::Brush],
@@ -983,9 +985,10 @@ struct BrushSearch<'a> {
exhausted: bool,
}
impl<'a> BrushSearch<'a> {
fn new(doc: &'a Document, brushes: &'a [vectorcraft_brush::Brush]) -> Self {
Self { doc, brushes, seen: HashMap::new(), left: MAX_KNOCKOUT_MASK_OBJECTS, exhausted: false }
impl<'a, 'd> BrushSearch<'a, 'd> {
/// A search through the document of `symbols`.
fn new(symbols: &'a vectorcraft_doc::SymbolBoxes<'d>, brushes: &'a [vectorcraft_brush::Brush]) -> Self {
Self { doc: symbols.document(), symbols, brushes, seen: HashMap::new(), left: MAX_KNOCKOUT_MASK_OBJECTS, exhausted: false }
}
/// Takes `n` objects from [`Self::left`]; false, and the search exhausted, when fewer are left.
@@ -1046,8 +1049,7 @@ impl<'a> BrushSearch<'a> {
NodeKind::SymbolInstance { symbol, .. } => {
// A dynamic symbol's instance draws its art with its own appearance changes: the
// art is copied once for each set of changes, counted before it is copied.
let doc = self.doc;
match doc.symbols.iter().find(|s| &s.name == symbol) {
match self.symbols.symbol(symbol) {
Some(s) if !n.extras().symbol_overrides.is_empty() => {
let key = format!("{symbol}\u{0}{:?}", n.extras().symbol_overrides);
self.shared(SharedArt::Dynamic, &key, |search| {
@@ -1080,8 +1082,7 @@ impl<'a> BrushSearch<'a> {
/// Whether the art of the symbol named `name` draws a brushed stroke.
fn symbol(&mut self, name: &str, depth: usize) -> bool {
let doc = self.doc;
let Some(s) = doc.symbols.iter().find(|s| s.name == name) else { return false };
let Some(s) = self.symbols.symbol(name) else { return false };
self.shared(SharedArt::Symbol, name, |search| search.node(&s.art, true, depth))
}
@@ -1177,7 +1178,8 @@ mod tests {
let square = Node::path(NodeId(0), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::basic(Paint::None, Paint::None, 0.0));
let art = Node::group(NodeId(0), vec![Arc::new(square), Arc::new(instance())]);
d.symbols.push(Symbol { dynamic: true, name: "Loop".into(), art: Arc::new(art) });
let mut search = BrushSearch::new(&d, &[]);
let symbols = d.symbol_boxes();
let mut search = BrushSearch::new(&symbols, &[]);
assert!(!search.node(&instance(), true, 0));
assert!(!search.exhausted);
assert!(MAX_KNOCKOUT_MASK_OBJECTS - search.left < 10, "{} objects", MAX_KNOCKOUT_MASK_OBJECTS - search.left);
@@ -1205,11 +1207,12 @@ mod tests {
.collect();
Node::group(NodeId(0), instances)
};
let mut search = BrushSearch::new(&d, &[]);
let symbols = d.symbol_boxes();
let mut search = BrushSearch::new(&symbols, &[]);
assert!(search.node(&group(true), true, 0));
assert!(search.exhausted);
assert_eq!(search.left, 0);
let mut search = BrushSearch::new(&d, &[]);
let mut search = BrushSearch::new(&symbols, &[]);
assert!(!search.node(&group(false), true, 0));
assert!(!search.exhausted);
// The group, the 1,000 instances, and one copy of the art counted and looked through.
@@ -1247,6 +1250,6 @@ mod tests {
vectorcraft_doc::placed_document::prime(&placed, Arc::new(vec![]), brushed_art());
let n = Node::new(NodeId(0), NodeKind::PlacedDocument(Box::new(placed)));
let brushes = vectorcraft_brush::library(&d);
assert!(BrushSearch::new(&d, &brushes).node(&n, true, 0));
assert!(BrushSearch::new(&d.symbol_boxes(), &brushes).node(&n, true, 0));
}
}
+1 -1
View File
@@ -134,7 +134,7 @@ impl Exporter<'_> {
self.inline_depth += 1;
for ig in &layout.inlines {
let Some(art) = t.runs.get(ig.run).and_then(|r| r.inline.as_ref()) else { continue };
let Some(sym) = doc.symbols.iter().find(|x| x.name == art.symbol) else { continue };
let Some(sym) = self.symbols.symbol(&art.symbol) else { continue };
let mut node = (*sym.art).clone();
// Strokes scale with the art, as on the canvas.
node.transform(t.xf * ig.xf * doc.symbol_natural_xf(&art.symbol), true);
+22 -10
View File
@@ -1,6 +1,6 @@
use super::entry::{INVISIBLE_TEXT_NOTE, MAX_NESTED, OUTLINED_TEXT_NOTE, UNSORTED, WHITE_KEY};
use super::state::{
Builder, Decoded, Frame, FrameKind, GlyphRun, blend, fill_rule, gray_png, line_width, mean_scale, resize_alpha, rgba_png, same_outline,
Builder, Decoded, Frame, FrameKind, GlyphRun, blend, fill_rule, gray_png, line_width, mean_scale, resize_alpha, rgb_png, rgba_png, same_outline,
stroke_layer, stroke_outline,
};
use super::{
@@ -304,27 +304,39 @@ impl<'a> Device<'a> for Builder<'_> {
self.add_image(key, || None, xf);
return;
}
let mut decoded: Option<Decoded> = None;
// RGB samples, or RGBA when the image has an alpha channel or is drawn white.
let mut decoded: Option<(Decoded, bool)> = None;
r.with_rgba(
|img, alpha| {
let (w, h, sf) = (img.width(), img.height(), img.scale_factors());
let a = alpha.map(|a| resize_alpha(&a, w, h)).unwrap_or_else(|| vec![255; (w * h) as usize]);
let rgba: Vec<u8> = match img {
_ if white => a.into_iter().flat_map(|a| [255, 255, 255, a]).collect(),
ImageData::Rgb(d) => d.data.as_chunks::<3>().0.iter().zip(a).flat_map(|(c, a)| [c[0], c[1], c[2], a]).collect(),
ImageData::Luma(d) => d.data.iter().zip(a).flat_map(|(g, a)| [*g, *g, *g, a]).collect(),
let px = match (img, alpha) {
// An opaque image's RGB samples are encoded as they are, with no copy.
(ImageData::Rgb(d), None) if !white => (d.data, false),
// Gray samples are stored as RGB: as a gray PNG, the image would become a
// grayscale image that a fill color colorizes.
(ImageData::Luma(d), None) if !white => (d.data.iter().flat_map(|g| [*g; 3]).collect(), false),
(img, alpha) => {
let a = alpha.map(|a| resize_alpha(&a, w, h)).unwrap_or_else(|| vec![255; (w * h) as usize]);
let rgba: Vec<u8> = match img {
_ if white => a.into_iter().flat_map(|a| [255, 255, 255, a]).collect(),
ImageData::Rgb(d) => d.data.as_chunks::<3>().0.iter().zip(a).flat_map(|(c, a)| [c[0], c[1], c[2], a]).collect(),
ImageData::Luma(d) => d.data.iter().zip(a).flat_map(|(g, a)| [*g, *g, *g, a]).collect(),
};
(rgba, true)
}
};
decoded = Some((rgba, w, h, sf));
decoded = Some(((px.0, w, h, sf), px.1));
},
None,
);
let Some((rgba, w, h, sf)) = decoded else {
let Some(((px, w, h, sf), alpha)) = decoded else {
self.warn("an image could not be decoded and was skipped");
return;
};
self.raster_scales.insert(key, sf);
let xf = transform * Affine::scale_non_uniform(sf.0 as f64, sf.1 as f64);
self.add_image(key, || rgba_png(rgba, w, h).map(|png| (ImageBlob::new("image/png", png), w, h)), xf);
let png = move || if alpha { rgba_png(px, w, h) } else { rgb_png(px, w, h) };
self.add_image(key, || png().map(|png| (ImageBlob::new("image/png", png), w, h)), xf);
}
Image::Stencil(s) => {
let white = self.white_images;
+5
View File
@@ -340,6 +340,11 @@ pub(super) fn rgba_png(rgba: Vec<u8>, w: u32, h: u32) -> Option<Vec<u8>> {
craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok()
}
pub(super) fn rgb_png(rgb: Vec<u8>, w: u32, h: u32) -> Option<Vec<u8>> {
let img = craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, rgb).ok()?;
craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok()
}
pub(super) fn gray_png(gray: Vec<u8>, w: u32, h: u32) -> Option<Vec<u8>> {
let img = craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, gray).ok()?;
craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok()
+7 -4
View File
@@ -215,7 +215,7 @@ fn stream_kind(pdf: &Pdf, id: ObjectIdentifier, dict: &Dict<'_>) -> String {
}
/// `bytes` for a message, in whole megabytes, or gigabytes when it is a whole number of them.
fn decoded_size(bytes: usize) -> String {
pub(crate) fn decoded_size(bytes: usize) -> String {
const GB: usize = 1 << 30;
if bytes >= GB && bytes.is_multiple_of(GB) { format!("{} GB", bytes / GB) } else { format!("{} MB", bytes >> 20) }
}
@@ -323,10 +323,13 @@ pub struct TrimPages {
pub bleed: [f64; 4],
}
/// Preserve the application's existing accepted file sizes. Ordinary stream decoding still
/// uses the shared reader's immutable per-document limits, and its input copy is fallible.
/// The shared reader's options: files of any size are accepted. Ordinary stream decoding uses the shared reader's immutable per-document limits, and its input
/// copy is fallible. One image may decode to the bytes and pixels of
/// [`crate::streams::image_limits`] for this build, past the shared reader's defaults.
pub(crate) fn open_options() -> craft_pdf::OpenOptions {
craft_pdf::OpenOptions { max_input_bytes: usize::MAX, ..Default::default() }
let (bytes, pixels) = crate::streams::image_limits(crate::streams::LARGE_IMAGES);
let decode_limits = craft_pdf::syntax::DecodeLimits::default().with_max_decoded_image(bytes).with_max_image_pixels(pixels);
craft_pdf::OpenOptions { max_input_bytes: usize::MAX, decode_limits }
}
pub(crate) fn open_with_options(bytes: &[u8], password: Option<&str>, options: &craft_pdf::OpenOptions) -> Result<Pdf, PdfError> {
+98 -16
View File
@@ -15,9 +15,21 @@ use craft_pdf::syntax::object::{Array, Dict, FromBytes, MaybeRef, Name, Object,
/// million, 4 bytes each).
pub(crate) const MAX_DECODED: usize = 256 << 20;
/// Whether this build reads the larger images of [`image_limits`]: a 64-bit build that isn't for
/// the web.
pub(crate) const LARGE_IMAGES: bool = cfg!(all(target_pointer_width = "64", not(target_family = "wasm")));
/// The most bytes one image XObject may decode to and the most pixels it may have, for a build
/// that reads `large` images: 4 GiB and 2^30 pixels (31404 × 31403 pixels are 2.76 GiB in RGB and
/// 3.67 GiB in CMYK), otherwise 1 GiB and 2^28 pixels (an A0 sheet scanned at 300 ppi is 399 MiB
/// in RGB and 532 MiB in CMYK). The shared reader takes the same two figures ([`crate::pages::open_options`]).
pub(crate) const fn image_limits(large: bool) -> (u64, u64) {
if large { (1 << 32, 1 << 30) } else { (1 << 30, 1 << 28) }
}
/// The most an image XObject may decode to when its own size asks for more than
/// [`MAX_DECODED`]: 1 GB (an A0 sheet scanned at 300 ppi is 418 MB in RGB, 557 MB in CMYK).
const MAX_IMAGE_DECODED: usize = 1 << 30;
/// [`MAX_DECODED`]: the bytes of [`image_limits`] for this build.
const MAX_IMAGE_DECODED: usize = image_limits(LARGE_IMAGES).0 as usize;
/// The longest row a predictor may have, in bytes.
const MAX_ROW: usize = 1 << 24;
@@ -779,31 +791,42 @@ mod tests {
/// A one-page PDF drawing one flat 8-bit DeviceRGB image of `w` × `h` pixels, Flate-compressed.
fn one_image_pdf(w: usize, h: usize) -> Vec<u8> {
image_pdf(&format!("/Width {w} /Height {h} /ColorSpace /DeviceRGB"), &flat(&[200, 180, 150].repeat(w), h), None)
}
/// `row` repeated `h` times, Flate-compressed as it is written.
fn flat(row: &[u8], h: usize) -> Vec<u8> {
let mut e = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::best());
let row: Vec<u8> = [200, 180, 150].repeat(w);
for _ in 0..h {
std::io::Write::write_all(&mut e, &row).unwrap();
std::io::Write::write_all(&mut e, row).unwrap();
}
let image = e.finish().unwrap();
e.finish().unwrap()
}
/// A one-page PDF drawing one 8-bit image with the size and color space of `keys` and the
/// Flate-compressed samples `data`; with `smask`, a soft mask with those keys and data.
fn image_pdf(keys: &str, data: &[u8], smask: Option<(&str, &[u8])>) -> Vec<u8> {
let stream = |keys: &str, data: &[u8]| {
let dict =
format!("<< /Type /XObject /Subtype /Image {keys} /BitsPerComponent 8 /Filter /FlateDecode /Length {} >>\nstream\n", data.len());
[dict.as_bytes(), data, b"\nendstream"].concat()
};
let content = b"q 595 0 0 842 0 0 cm /Im0 Do Q";
let mut out = b"%PDF-1.6\n".to_vec();
let mut offsets = vec![];
let objects: Vec<Vec<u8>> = vec![
let mut objects: Vec<Vec<u8>> = vec![
b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(),
b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(),
b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 595 842] /Contents 4 0 R /Resources << /XObject << /Im0 5 0 R >> >> >>".to_vec(),
[format!("<< /Length {} >>\nstream\n", content.len()).as_bytes(), content, b"\nendstream"].concat(),
[
format!(
"<< /Type /XObject /Subtype /Image /Width {w} /Height {h} /ColorSpace /DeviceRGB /BitsPerComponent 8 /Filter /FlateDecode /Length {} >>\nstream\n",
image.len()
)
.as_bytes(),
&image,
b"\nendstream",
]
.concat(),
];
match smask {
Some((mask_keys, mask_data)) => {
objects.push(stream(&format!("{keys} /SMask 6 0 R"), data));
objects.push(stream(mask_keys, mask_data));
}
None => objects.push(stream(keys, data)),
}
for (i, o) in objects.iter().enumerate() {
offsets.push(out.len());
out.extend_from_slice(format!("{} 0 obj\n", i + 1).as_bytes());
@@ -828,6 +851,65 @@ mod tests {
assert_eq!(info.map(|i| i.pages.len()).unwrap(), 1);
}
#[test]
fn a_64_bit_desktop_build_reads_larger_images_and_others_keep_their_limits() {
assert_eq!(image_limits(false), (1 << 30, 1 << 28));
assert_eq!(image_limits(true), (1 << 32, 1 << 30));
let (bytes, pixels) = image_limits(LARGE_IMAGES);
assert_eq!(MAX_IMAGE_DECODED as u64, bytes);
let limits = crate::pages::open_options().decode_limits;
assert_eq!((limits.max_decoded_image(), limits.max_image_pixels()), (bytes, pixels));
// An image declaring more is held to this build's limit, which a refusal of it names.
let d = dict("<< /Subtype /Image /Width 70000 /Height 70000 /ColorSpace /DeviceRGB /BitsPerComponent 8 /Filter /FlateDecode >>");
assert_eq!(budget(&d), MAX_IMAGE_DECODED);
let most = if LARGE_IMAGES { "4 GB" } else { "1 GB" };
assert_eq!(crate::pages::decoded_size(MAX_IMAGE_DECODED), most);
}
/// The only image of `doc`, as stored: its width, height and channel layout.
fn stored_image(doc: &vectorcraft_doc::Document) -> (u32, u32, image::ExtendedColorType) {
use image::ImageDecoder as _;
let blobs: Vec<_> = doc.images.values().collect();
let [blob] = blobs[..] else { panic!("one image expected, found {}", blobs.len()) };
let decoder = image::ImageReader::new(std::io::Cursor::new(blob.bytes.as_slice())).with_guessed_format().unwrap().into_decoder().unwrap();
let (w, h) = decoder.dimensions();
(w, h, decoder.original_color_type())
}
#[test]
fn an_image_past_1_gb_and_2_to_the_28_pixels_opens_on_a_64_bit_desktop_build() {
if !LARGE_IMAGES {
return;
}
// 18919 × 18919 RGB pixels: 358 million pixels, 1.07 GB decoded (#4366).
let side = 18919;
let doc = crate::import(&one_image_pdf(side, side)).unwrap();
// Opaque: stored as RGB, without an alpha channel.
assert_eq!(stored_image(&doc), (side as u32, side as u32, image::ExtendedColorType::Rgb8));
}
#[test]
fn opaque_images_are_stored_without_an_alpha_channel_and_masked_ones_with_one() {
let rgb = image_pdf("/Width 4 /Height 2 /ColorSpace /DeviceRGB", &flat(&[200, 180, 150].repeat(4), 2), None);
assert_eq!(stored_image(&crate::import(&rgb).unwrap()), (4, 2, image::ExtendedColorType::Rgb8));
let gray = image_pdf("/Width 4 /Height 2 /ColorSpace /DeviceGray", &flat(&[120; 4], 2), None);
assert_eq!(stored_image(&crate::import(&gray).unwrap()), (4, 2, image::ExtendedColorType::Rgb8));
let mask = ("/Width 4 /Height 2 /ColorSpace /DeviceGray", &flat(&[0, 85, 170, 255], 2)[..]);
let masked = image_pdf("/Width 4 /Height 2 /ColorSpace /DeviceRGB", &flat(&[200, 180, 150].repeat(4), 2), Some(mask));
assert_eq!(stored_image(&crate::import(&masked).unwrap()), (4, 2, image::ExtendedColorType::Rgba8));
}
#[test]
fn an_image_of_more_pixels_than_the_limit_is_left_out_with_a_warning() {
let (_, pixels) = image_limits(LARGE_IMAGES);
// One more row than a square of the limit's pixels; its data isn't looked at.
let side = 1u64 << (pixels.ilog2() / 2);
let pdf = image_pdf(&format!("/Width {side} /Height {} /ColorSpace /DeviceGray", side + 1), &flat(&[0; 16], 1), None);
let report = crate::import_with_report(&pdf, &crate::ImportOptions::default()).unwrap();
assert!(report.document.images.is_empty());
assert!(report.warnings.iter().any(|w| w.contains("an image could not be decoded and was skipped")), "{:?}", report.warnings);
}
#[test]
fn object_and_cross_reference_streams_are_looked_at_before_the_file_is_read() {
let stream = |dict: &str, data: &[u8]| {
+54
View File
@@ -223,6 +223,60 @@ fn an_instance_whose_art_reaches_the_page_is_written() {
assert!(fills.contains(&[255, 0, 0, 255]) && fills.contains(&[0, 0, 255, 255]), "{fills:?}");
}
/// 2,000 symbols, then two named "Mark" (a red square, then a blue one), with an instance of
/// "Mark" at (25, 25) and, in a knockout group above a green square, a half-opaque one at (70, 70).
/// With `second` the blue square's symbol is named that instead.
fn marks(second: &str) -> Document {
let mut d = doc(100.0, 100.0);
for i in 0..2000 {
let art = rect_node(Rect::new(0.0, 0.0, 1.0, 1.0), Color::BLACK);
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: format!("Filler {i}"), art: Arc::new(art) });
}
for (name, color) in [("Mark", Color::rgb(1.0, 0.0, 0.0)), (second, Color::rgb(0.0, 0.0, 1.0))] {
let art = rect_node(Rect::new(-10.0, -10.0, 10.0, 10.0), color);
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: name.into(), art: Arc::new(art) });
}
add(&mut d, Node::new(NodeId(0), NodeKind::SymbolInstance { symbol: "Mark".into(), xf: Affine::translate((25.0, 25.0)) }));
let green = rect_node(Rect::new(60.0, 60.0, 80.0, 80.0), Color::rgb(0.0, 1.0, 0.0));
let mut above = Node::new(NodeId(0), NodeKind::SymbolInstance { symbol: "Mark".into(), xf: Affine::translate((70.0, 70.0)) });
above.opacity = 0.5;
let mut group = Node::group(NodeId(0), vec![Arc::new(green), Arc::new(above)]);
group.knockout = vectorcraft_doc::Knockout::On;
add(&mut d, group);
d
}
/// Instances among many symbols are written with the first symbol of their name, the same bytes
/// as when no other symbol has that name.
#[test]
fn instances_are_written_with_the_first_symbol_of_their_name() {
let d = marks("Mark");
assert!(uncompressed(&d) == uncompressed(&marks("Other")), "the files differ");
let fills: Vec<[u8; 4]> = leaves(&roundtrip(&d)).iter().filter_map(|n| Some(n.appearance.fill_paint().color()?.to_rgba8(1.0))).collect();
assert!(fills.contains(&[255, 0, 0, 255]) && !fills.contains(&[0, 0, 255, 255]), "{fills:?}");
}
/// An export of 300 instances with drop shadows, among 2,000 symbols, reads the symbol list once
/// to find their symbols.
#[test]
fn an_export_reads_the_symbol_list_once() {
let mut d = marks("Other");
for i in 0..300 {
let xf = Affine::translate((f64::from(i % 20) * 5.0, f64::from(i / 20) * 5.0)) * Affine::scale(0.2);
let mut n = Node::new(NodeId(0), NodeKind::SymbolInstance { symbol: "Mark".into(), xf });
n.appearance.effects.push(vectorcraft_doc::Effect {
id: "stylize.dropShadow".into(),
params: serde_json::json!({"x": 1, "y": 1, "blur": 0}),
visible: true,
});
add(&mut d, n);
}
let before = vectorcraft_doc::symbols_read();
export(&d, &PdfOptions::default()).expect("export");
let read = vectorcraft_doc::symbols_read() - before;
assert!(read <= d.symbols.len(), "{read} symbols read, {} in the document", d.symbols.len());
}
#[test]
fn an_instance_whose_brush_art_reaches_the_page_is_written() {
// The symbol's art: a line from (0, 40) to (0, 60) with a 1 pt stroke painted by a 20 pt round
+2
View File
@@ -51,3 +51,5 @@ craft-tiff = { workspace = true }
craft-psd = { workspace = true }
proptest = { workspace = true }
serde_json = { workspace = true }
# How many times the symbol list is read to find symbols by name.
vectorcraft-doc = { workspace = true, features = ["symbol-read-count"] }
+1 -1
View File
@@ -57,7 +57,7 @@ pub fn sample(doc: &Document, nodes: Vec<Node>, region: Rect, scale: f64, mono:
/// take too many cells: `n` then draws as it is.
pub fn art(doc: &Document, n: &Node) -> Option<Node> {
let ht = Halftone::of(n)?;
let found = Renderer::new().live_found(doc, &Arc::new(n.clone()));
let found = Renderer::new().live_found(&doc.symbol_boxes(), &Arc::new(n.clone()));
let mut cache = CACHE.lock().unwrap_or_else(PoisonError::into_inner);
if let Some(at) = cache.iter().position(|(node, was, _)| was.0 == found.0 && node == n) {
let kept = cache.remove(at);
+8 -2
View File
@@ -6,7 +6,13 @@ use super::{BezPath, Document, FillRule, Node, NodeKind, Rect, SymbolBoxes, brus
/// geometry effects, and the shadows and glows of it and its members. Symbol instances are
/// measured by their art in `doc` ([`Node::visual_bounds_with`]).
pub fn painted_bounds(doc: &Document, n: &Node) -> Option<Rect> {
brush_fx::cull_bounds(&doc.symbol_boxes(), n)
painted_bounds_with(&doc.symbol_boxes(), n)
}
/// [`painted_bounds`] with symbol instances measured by their art in `symbols` (made with
/// [`Document::symbol_boxes`]).
pub fn painted_bounds_with(symbols: &SymbolBoxes, n: &Node) -> Option<Rect> {
brush_fx::cull_bounds(symbols, n)
}
/// [`painted_bounds`] of `n` without the room it leaves for brush art past the brushed strokes of
@@ -70,7 +76,7 @@ pub fn rasterize_stage(doc: &Document, n: &Node) -> Option<(Node, Vec<vectorcraf
/// The outline, with `n`'s geometry effects applied, that the canvas clips `n`'s Rasterize with
/// Create Clipping Mask to. Object › Rasterize's clipping mask follows it.
pub fn drawn_outline(doc: &Document, n: &Node) -> Option<(BezPath, FillRule)> {
fx::drawn_outline(doc, n)
fx::drawn_outline(&doc.symbol_boxes(), n)
}
/// The outlines a drag draws for `nodes` with Real-time Drawing off: one for each object in them,
+11 -13
View File
@@ -397,9 +397,7 @@ fn shape_bounds(symbols: &SymbolBoxes, n: &Node) -> Option<Rect> {
// effects in a symbol's art and a live object's content paint past it.
_ if has_object_fx(n) => {
let symbol = match &n.kind {
NodeKind::SymbolInstance { symbol, .. } => {
symbols.document().symbols.iter().find(|s| s.name == *symbol).map(|s| dynamic_art(&s.art, n))
}
NodeKind::SymbolInstance { symbol, .. } => symbols.symbol(symbol).map(|s| dynamic_art(&s.art, n)),
_ => None,
};
let reshaped = effects::reshape(Some(symbols.document()), n, symbol.as_ref());
@@ -466,7 +464,7 @@ fn pieces_within(symbols: &SymbolBoxes, art: &Node, depth: usize, budget: &mut u
NodeKind::Path { .. } | NodeKind::Compound { .. } if has_fx(art) => visual_bounds(symbols, art),
NodeKind::SymbolInstance { symbol, .. } if depth < vectorcraft_doc::depth::MAX_DEPTH && has_instance_row_effects(art) => {
let doc = symbols.document();
let reshaped = doc.symbols.iter().find(|s| s.name == *symbol).and_then(|s| {
let reshaped = symbols.symbol(symbol).and_then(|s| {
let count = s.art.count() as u64;
if count > *budget {
return None;
@@ -501,13 +499,15 @@ pub(crate) fn painted_reach(symbols: &SymbolBoxes, n: &Node) -> Option<Rect> {
/// The outline the renderer clips `n`'s Feather, Inner Glow and Rasterize with Create Clipping
/// Mask to: a path's or compound path's geometry with its object-level geometry effects applied,
/// the outline of the art [`Renderer::fx_art`] makes for an object with object effects, and with
/// Crop Marks the object's own. For other objects it is [`effects::clip_outline`].
pub(crate) fn drawn_outline(doc: &Document, n: &Node) -> Option<(BezPath, FillRule)> {
/// Crop Marks the object's own. For other objects it is [`effects::clip_outline`]. The symbols of
/// instances are found in `symbols`.
pub(crate) fn drawn_outline(symbols: &SymbolBoxes, n: &Node) -> Option<(BezPath, FillRule)> {
let doc = symbols.document();
if let Some(art) = effects::crop_marks_art(n) {
return drawn_outline(doc, art.children()?.first()?);
return drawn_outline(symbols, art.children()?.first()?);
}
if has_object_fx(n) {
let art = Renderer::new().fx_art(doc, &Arc::new(n.clone()), false);
let art = Renderer::new().fx_art(symbols, &Arc::new(n.clone()), false);
return effects::clip_outline(&art);
}
match &n.kind {
@@ -545,7 +545,7 @@ pub(crate) fn drawn_outlines(doc: &Document, symbols: &SymbolBoxes, n: &Node, le
if is_container(n) && !makes_art && !effects::has_item_geometry(n) {
object.appearance.items.clear();
}
let art = Renderer::new().fx_art(doc, &Arc::new(object), false);
let art = Renderer::new().fx_art(symbols, &Arc::new(object), false);
if art.children().is_some() && !has_object_fx(&art) {
return evaluated_outlines(doc, symbols, &art, left, out);
}
@@ -570,7 +570,7 @@ pub(crate) fn drawn_outlines(doc: &Document, symbols: &SymbolBoxes, n: &Node, le
NodeKind::SymbolInstance { .. } => {
push_outline(n.geometric_bounds_with(symbols).map(|b| vectorcraft_geom::shapes::rectangle(b).to_bezpath()), left, out)
}
_ => push_outline(drawn_outline(doc, n).map(|(path, _)| path), left, out),
_ => push_outline(drawn_outline(symbols, n).map(|(path, _)| path), left, out),
}
}
@@ -690,9 +690,7 @@ fn cull_bounds_in(symbols: &SymbolBoxes, n: &Node, after_reshape: bool, brush: b
// symbol instance's art paint past that art.
_ if has_object_fx(n) => {
let symbol = match &n.kind {
NodeKind::SymbolInstance { symbol, .. } => {
symbols.document().symbols.iter().find(|s| s.name == *symbol).map(|s| dynamic_art(&s.art, n))
}
NodeKind::SymbolInstance { symbol, .. } => symbols.symbol(symbol).map(|s| dynamic_art(&s.art, n)),
_ => None,
};
let reshaped = effects::reshape(Some(symbols.document()), n, symbol.as_ref());
+18 -19
View File
@@ -481,7 +481,7 @@ impl Renderer {
/// What [`Self::draw_object_fx`] draws inside the object's transparency group.
fn draw_object_fx_art(&mut self, ctx: &mut RenderContext, f: &Frame, a: &Arc<Node>, cache: bool) {
if !self.charge_fx_instance(f.doc, a) {
if !self.charge_fx_instance(f.symbols, a) {
return;
}
// A path whose Transform effects after its Rasterize effect hold options that reach its
@@ -493,7 +493,7 @@ impl Renderer {
{
return self.draw_staged(ctx, f, stage, &bp, *rule);
}
let art = self.fx_art(f.doc, a, cache);
let art = self.fx_art(f.symbols, a, cache);
// Art the cache did not keep is made again in the next frame.
let kept = cache && self.fx_arts.get(&(Arc::as_ptr(a) as usize), self.stamp).is_some_and(|e| Arc::ptr_eq(&e.1, &art));
let outer = self.made_again;
@@ -545,9 +545,9 @@ impl Renderer {
/// frame's symbol budget as an instance without effects is (`draw_node`): an instance whose
/// effects reshape its art draws through here, and nested instances would otherwise expand
/// without a limit. True for any other object.
pub(crate) fn charge_fx_instance(&mut self, doc: &vectorcraft_doc::Document, a: &Node) -> bool {
pub(crate) fn charge_fx_instance(&mut self, symbols: &SymbolBoxes, a: &Node) -> bool {
let NodeKind::SymbolInstance { symbol, .. } = &a.kind else { return true };
let count = doc.symbols.iter().find(|s| &s.name == symbol).map_or(0, |s| s.art.count() as u64);
let count = symbols.symbol(symbol).map_or(0, |s| s.art.count() as u64);
let mut used = self.symbol_nodes;
let room = vectorcraft_doc::charge_symbol_art(&mut used, count, || ((), count)).is_some();
self.symbol_nodes = used;
@@ -562,7 +562,7 @@ impl Renderer {
/// is made from live objects it evaluated ([`evaluates_live`]), or from type, symbol art or
/// colors shaded through the color settings ([`reads_outside`]), is kept only while what it
/// reads from outside `a` stays the same ([`Self::live_found`]).
pub(super) fn fx_art(&mut self, doc: &vectorcraft_doc::Document, a: &Arc<Node>, cache: bool) -> Arc<Node> {
pub(super) fn fx_art(&mut self, symbols: &SymbolBoxes, a: &Arc<Node>, cache: bool) -> Arc<Node> {
let key = Arc::as_ptr(a) as usize;
let mut kept = None;
if cache
@@ -574,7 +574,7 @@ impl Renderer {
Some(was) => kept = Some((art.clone(), was.0)),
}
}
let found = (kept.is_some() || (cache && (evaluates_live(a) || reads_outside(a)))).then(|| self.live_found(doc, a));
let found = (kept.is_some() || (cache && (evaluates_live(a) || reads_outside(a)))).then(|| self.live_found(symbols, a));
if let Some((art, was)) = kept
&& found.as_ref().is_some_and(|f| f.0 == was)
{
@@ -590,11 +590,11 @@ impl Renderer {
Some((art, was)) => {
let now = match &found {
Some(f) => Some(f.0),
None => self.outside_key(doc, a),
None => self.outside_key(symbols, a),
};
if was == now { art } else { self.make_fx_art(doc, a) }
if was == now { art } else { self.make_fx_art(symbols, a) }
}
None => self.make_fx_art(doc, a),
None => self.make_fx_art(symbols, a),
};
if cache {
let bytes = crate::lru::node_bytes(&art);
@@ -607,24 +607,24 @@ impl Renderer {
/// held until the frame ends ([`Renderer::measured`]), for [`Self::fx_art`] to keep if `a` is
/// drawn. What is measured but never drawn (culled, off the view) is let go, and isn't kept in
/// place of what is drawn.
pub(crate) fn measured_fx_art(&mut self, doc: &vectorcraft_doc::Document, a: &Arc<Node>) -> Arc<Node> {
pub(crate) fn measured_fx_art(&mut self, symbols: &SymbolBoxes, a: &Arc<Node>) -> Arc<Node> {
let key = Arc::as_ptr(a) as usize;
if let Some((node, art, found)) = self.fx_arts.get(&key, self.stamp)
&& Arc::ptr_eq(node, a)
{
let (art, was) = (art.clone(), found.as_ref().map(|f| f.0));
if was.is_none_or(|was| self.live_found(doc, a).0 == was) {
if was.is_none_or(|was| self.live_found(symbols, a).0 == was) {
return art;
}
}
let now = self.outside_key(doc, a);
let now = self.outside_key(symbols, a);
if let Some((node, art, was)) = self.measured.get(&key)
&& Arc::ptr_eq(node, a)
&& *was == now
{
return art.clone();
}
let art = self.make_fx_art(doc, a);
let art = self.make_fx_art(symbols, a);
// Art held for an object before (made from what it read then) gives way.
if let Some(old) = self.measured.remove(&key) {
self.measured_bytes = self.measured_bytes.saturating_sub(crate::lru::node_bytes(&old.1));
@@ -657,18 +657,17 @@ impl Renderer {
/// The key of what `a`'s art reads from outside it ([`Self::live_found`]), `None` when it reads
/// nothing.
fn outside_key(&mut self, doc: &vectorcraft_doc::Document, a: &Arc<Node>) -> Option<u64> {
(evaluates_live(a) || reads_outside(a)).then(|| self.live_found(doc, a).0)
fn outside_key(&mut self, symbols: &SymbolBoxes, a: &Arc<Node>) -> Option<u64> {
(evaluates_live(a) || reads_outside(a)).then(|| self.live_found(symbols, a).0)
}
/// The art [`Self::fx_art`] draws for `a`, made now.
fn make_fx_art(&mut self, doc: &vectorcraft_doc::Document, a: &Arc<Node>) -> Arc<Node> {
fn make_fx_art(&mut self, symbols: &SymbolBoxes, a: &Arc<Node>) -> Arc<Node> {
let doc = symbols.document();
// Whether the art is a 3D effect's ([`Self::three_d_art_bounds`]).
let mut three_d = false;
let symbol = match &a.kind {
NodeKind::SymbolInstance { symbol, .. } => {
doc.symbols.iter().find(|s| s.name == *symbol).map(|s| crate::brush_fx::instance_art(&s.art, a))
}
NodeKind::SymbolInstance { symbol, .. } => symbols.symbol(symbol).map(|s| crate::brush_fx::instance_art(&s.art, a)),
_ => None,
};
let container = is_container(a);
+4 -4
View File
@@ -1066,7 +1066,7 @@ fn a_measuring_pass_sweeps_the_bounds_of_held_art_as_they_double() {
}
let mut r = Renderer::new();
// Held here, as the art kept to draw is.
let held: Vec<_> = d.layers[0].children().unwrap().iter().map(|n| r.measured_fx_art(&d, n)).collect();
let held: Vec<_> = d.layers[0].children().unwrap().iter().map(|n| r.measured_fx_art(&d.symbol_boxes(), n)).collect();
assert_eq!((held.len(), r.three_d_bounds.len()), (3000, 3000));
assert!(r.three_d_sweeps <= 2, "{} sweeps", r.three_d_sweeps);
}
@@ -1193,7 +1193,7 @@ fn drawing_takes_measured_art_out_of_the_budget() {
let mut r = Renderer::new();
r.bounds_of(&d.symbol_boxes(), &n);
assert!(r.measured_bytes > 0);
r.fx_art(&d, &n, true);
r.fx_art(&d.symbol_boxes(), &n, true);
assert_eq!((r.measured_bytes, r.measured.len()), (0, 0), "taken out when drawn");
let mut r = Renderer::new();
r.render(&d, 800, 100, Affine::IDENTITY, &RenderOptions::default());
@@ -1343,11 +1343,11 @@ fn art_measured_again_takes_the_place_of_the_held() {
let n = d.layers[0].children().unwrap()[0].clone();
let key = Arc::as_ptr(&n) as usize;
let mut r = Renderer::new();
let art = r.measured_fx_art(&d, &n);
let art = r.measured_fx_art(&d.symbol_boxes(), &n);
let bytes = r.measured_bytes;
// As if it had read something else then.
r.measured.insert(key, (n.clone(), art, Some(7)));
r.measured_fx_art(&d, &n);
r.measured_fx_art(&d.symbol_boxes(), &n);
assert_eq!((r.measured_bytes, r.measured.len()), (bytes, 1));
}
+1 -1
View File
@@ -285,7 +285,7 @@ mod renderer;
mod text_geom;
mod threads;
pub use bounds::{drawn_bounds, drawn_outline, drawn_outlines, effect_bounds, painted_bounds, rasterize_stage};
pub use bounds::{drawn_bounds, drawn_outline, drawn_outlines, effect_bounds, painted_bounds, painted_bounds_with, rasterize_stage};
pub use frame::FrameStats;
use frame::{
ClipEntry, ClipPaintEntry, Frame, FxArtEntry, GeomEntry, PlacedEntry, PlacedKey, PtrHasher, PtrMap, SliceEntry, StrokeEntry, StrokeKey,
+40 -23
View File
@@ -21,7 +21,7 @@ use std::sync::{Arc, Weak};
use vectorcraft_doc::live::{GradientMesh, MeshQuad};
use vectorcraft_doc::placed_document::ReadDocument;
use vectorcraft_doc::{Document, Node, NodeKind};
use vectorcraft_doc::{Document, Node, NodeKind, SymbolBoxes};
use vectorcraft_geom::{Affine, BezPath, Point, Vec2};
use vello_cpu::RenderContext;
use vello_cpu::peniko;
@@ -109,10 +109,11 @@ pub fn expand_live(n: &Node) -> Vec<Node> {
/// their address). Art is hashed by the addresses of its `Arc`s, which copies of the document
/// share: a copy of the document has the same key. It also returns weak references to the reads
/// found, and what the walk found ([`Walked`]) when it found no placed file and no such image.
fn resources_key(doc: &Document, cms: usize, names: u64, n: &Node) -> (u64, Vec<Weak<ReadDocument>>, Option<Walked>) {
/// Symbols are found by name in `symbols`.
fn resources_key(symbols: &SymbolBoxes, cms: usize, names: u64, n: &Node) -> (u64, Vec<Weak<ReadDocument>>, Option<Walked>) {
let mut h = DefaultHasher::new();
let mut shown = Shown::default();
hash_resources(doc, n, &mut shown, &mut h);
hash_resources(symbols, n, &mut shown, &mut h);
let walked = Walked { hash: h.finish(), text: shown.text, plugins: shown.plugins };
(walked.key(cms, names), shown.reads, (!shown.placed && !shown.pixels).then_some(walked))
}
@@ -175,8 +176,9 @@ struct Shown {
/// own fills or strokes follow them ([`crate::effects::follows_image_pixels`]). It walks `n` and
/// then, one at a time from a list, the opacity-mask, pattern and symbol art it finds, each pattern
/// and each symbol's art once ([`first_seen`]). `shown` records the type, placed files, reads,
/// such images and plug-in effects found.
fn hash_resources<'a>(doc: &'a Document, n: &'a Node, shown: &mut Shown, h: &mut DefaultHasher) {
/// such images and plug-in effects found. Symbols are found by name in `symbols`.
fn hash_resources<'a>(symbols: &SymbolBoxes<'a>, n: &'a Node, shown: &mut Shown, h: &mut DefaultHasher) {
let doc = symbols.document();
let mut todo = vec![];
let mut next = Some(n);
while let Some(art) = next {
@@ -198,7 +200,7 @@ fn hash_resources<'a>(doc: &'a Document, n: &'a Node, shown: &mut Shown, h: &mut
}
match &c.kind {
NodeKind::SymbolInstance { symbol, .. } => {
if let Some(s) = doc.symbols.iter().find(|s| s.name == *symbol) {
if let Some(s) = symbols.symbol(symbol) {
(Arc::as_ptr(&s.art) as usize).hash(h);
if first_seen(&mut shown.seen, Arc::as_ptr(&s.art) as usize) {
todo.push(&s.art);
@@ -249,6 +251,10 @@ fn mesh_level(m: &GradientMesh, bounds_px: f64) -> usize {
/// of pixels per mesh and frame.
const MESH_RASTER_MAX_PIXELS: usize = 4 << 20;
/// The widest and tallest a gradient mesh's outline is in device pixels for [`draw_mesh_raster`]
/// to flatten it (about 16.7 million pixels, far past any buffer it fills).
const MESH_OUTLINE_MAX_EXTENT: f64 = (1u32 << 24) as f64;
/// Draw a tessellated gradient mesh as one image: its quads are filled into a pixel buffer of the
/// mesh's on-screen box by scanline (each pixel takes the quad its centre is in, so neighbouring
/// quads meet without seams or overlap, and is shaded between the quad's corner colours, so the
@@ -262,7 +268,12 @@ const MESH_RASTER_MAX_PIXELS: usize = 4 << 20;
fn draw_mesh_raster(ctx: &mut RenderContext, f: &Frame, m: &GradientMesh, quads: &[MeshQuad], alpha: f32) -> bool {
let outline = m.outline().to_bezpath();
let dev = f.view.transform_rect_bbox(vectorcraft_geom::Shape::bounding_box(&outline));
if ![dev.x0, dev.y0, dev.x1, dev.y1].iter().all(|v| v.is_finite()) {
// The outline is flattened whole in device pixels ([`grown_outline`]): one far past any
// buffer would make more segments than memory holds, so the caller draws the quads.
if ![dev.x0, dev.y0, dev.x1, dev.y1].iter().all(|v| v.is_finite())
|| dev.width() > MESH_OUTLINE_MAX_EXTENT
|| dev.height() > MESH_OUTLINE_MAX_EXTENT
{
return false;
}
let (cw, ch) = (f64::from(ctx.width()), f64::from(ctx.height()));
@@ -453,14 +464,14 @@ fn spread_to_edges(px: &mut [vello_cpu::color::PremulRgba8], filled: Vec<bool>,
}
impl Renderer {
/// The [`resources_key`] of `n` in `doc`, with the frame's [`DocInputs`] ([`Found`]): `n` is a
/// live node, or an object with effects whose art ([`Renderer::fx_art`]) can be made from
/// evaluated live objects, type, symbol art or colors shaded through the color settings. The
/// key is made from the [`Walk`] kept for `n` while `doc`'s symbols and patterns are those it
/// read; `n` is walked again when they changed, and in every frame when the walk found a
/// placed file or an image whose own fills or strokes follow its pixels.
pub(crate) fn live_found(&mut self, doc: &Document, n: &Arc<Node>) -> Found {
let inputs = self.doc_inputs(doc);
/// The [`resources_key`] of `n` in the document of `symbols`, with the frame's [`DocInputs`]
/// ([`Found`]): `n` is a live node, or an object with effects whose art ([`Renderer::fx_art`])
/// can be made from evaluated live objects, type, symbol art or colors shaded through the color
/// settings. The key is made from the [`Walk`] kept for `n` while the document's symbols and
/// patterns are those it read; `n` is walked again when they changed, and in every frame when
/// the walk found a placed file or an image whose own fills or strokes follow its pixels.
pub(crate) fn live_found(&mut self, symbols: &SymbolBoxes, n: &Arc<Node>) -> Found {
let inputs = self.doc_inputs(symbols.document());
let at = Arc::as_ptr(n) as usize;
if let Some((node, walked, read)) = self.live.walks.get(&at, self.stamp)
&& std::ptr::eq(node.as_ptr(), Arc::as_ptr(n))
@@ -472,7 +483,7 @@ impl Renderer {
{
self.live.walked += 1;
}
let (key, reads, walked) = resources_key(doc, inputs.cms, inputs.names, n);
let (key, reads, walked) = resources_key(symbols, inputs.cms, inputs.names, n);
if let Some(walked) = walked {
// The bytes count the key and the entry, and the node's allocation that the weak
// reference keeps.
@@ -482,11 +493,12 @@ impl Renderer {
(key, inputs, reads)
}
fn live_expanded(&mut self, doc: &Document, a: &Arc<Node>, cache: bool) -> Expanded {
fn live_expanded(&mut self, symbols: &SymbolBoxes, a: &Arc<Node>, cache: bool) -> Expanded {
let doc = symbols.document();
let key = Arc::as_ptr(a) as usize;
// An evaluation the cache does not keep is made without the key, so the copy that
// `draw_live_node` makes is not walked.
let resources = cache.then(|| self.live_found(doc, a));
let resources = cache.then(|| self.live_found(symbols, a));
if let Some(resources) = &resources
&& let Some(e) = self.live.expanded.get(&key, self.stamp)
&& Arc::ptr_eq(&e.0, a)
@@ -541,7 +553,7 @@ impl Renderer {
let knockout = !f.opts.outline
&& matches!(a.kind, NodeKind::Blend { .. })
&& a.knockout.resolve(self.knockout)
&& vectorcraft_doc::live::steps_knockout_shows(&self.live_expanded(f.doc, a, true));
&& vectorcraft_doc::live::steps_knockout_shows(&self.live_expanded(f.symbols, a, true));
let enclosing = std::mem::replace(&mut self.knockout, knockout);
if !f.opts.outline && (opacity < 1.0 || a.blend != vectorcraft_color::BlendMode::Normal || a.isolate || knockout) {
let blends = self.blends_through(a);
@@ -566,7 +578,7 @@ impl Renderer {
| NodeKind::Intertwine { .. }
| NodeKind::Group { .. }
| NodeKind::Layer { .. } => {
let items = self.live_expanded(f.doc, a, cache);
let items = self.live_expanded(f.symbols, a, cache);
// An evaluation the cache did not keep is made again in the next frame.
let kept = cache && self.live.expanded.get(&(Arc::as_ptr(a) as usize), self.stamp).is_some_and(|e| Arc::ptr_eq(&e.1, &items));
let outer = self.made_again;
@@ -809,7 +821,12 @@ mod tests {
let envelope = Node::new(d.alloc_id(), envelope);
let key = |d: &Document| {
std::thread::scope(|s| {
std::thread::Builder::new().stack_size(256 << 10).spawn_scoped(s, || resources_key(d, 0, 0, &envelope).0).unwrap().join().unwrap()
std::thread::Builder::new()
.stack_size(256 << 10)
.spawn_scoped(s, || resources_key(&d.symbol_boxes(), 0, 0, &envelope).0)
.unwrap()
.join()
.unwrap()
})
};
let before = key(&d);
@@ -841,8 +858,8 @@ mod tests {
frame: Box::new(Affine::IDENTITY),
};
let envelope = Node::new(d.alloc_id(), envelope);
let before = resources_key(&d, 0, 0, &envelope).0;
let before = resources_key(&d.symbol_boxes(), 0, 0, &envelope).0;
d.symbols[2].art = y.clone();
assert_ne!(resources_key(&d, 0, 0, &envelope).0, before, "the art of every instance is hashed");
assert_ne!(resources_key(&d.symbol_boxes(), 0, 0, &envelope).0, before, "the art of every instance is hashed");
}
}
+2 -2
View File
@@ -36,7 +36,7 @@ impl Renderer {
// drawn otherwise, measured as below.
_ if measures_three_d(a)
&& let Some(b) = {
let art = self.measured_fx_art(symbols.document(), a);
let art = self.measured_fx_art(symbols, a);
self.three_d_art_bounds(symbols, &art)
} =>
{
@@ -578,7 +578,7 @@ impl Renderer {
self.draw_image_in(ctx, f, &f.doc.shown_image(n, im), None, images::image_tint(f.doc, n, f.ink), n.extras().pixelated)
}
NodeKind::SymbolInstance { symbol, xf } => {
if let Some(sym) = f.doc.symbols.iter().find(|s| &s.name == symbol) {
if let Some(sym) = f.symbols.symbol(symbol) {
// The instance draws when the frame has room for its art's objects; a symbol
// with 9-slice guides is placed cell by cell (`Self::sliced_art`).
let mut used = self.symbol_nodes;
+2 -2
View File
@@ -32,14 +32,14 @@ impl Renderer {
return;
}
for r in t.runs.iter().filter_map(|r| r.inline.as_ref()) {
if !f.doc.symbols.iter().any(|s| s.name == r.symbol) && !MISSING_INLINE_LOGGED.swap(true, std::sync::atomic::Ordering::Relaxed) {
if f.symbols.symbol(&r.symbol).is_none() && !MISSING_INLINE_LOGGED.swap(true, std::sync::atomic::Ordering::Relaxed) {
log::warn!("inline graphic shows symbol {:?}, which the document doesn't have: it draws nothing", r.symbol);
}
}
self.inline_depth += 1;
for ig in &g.inlines {
let Some(art) = t.runs.get(ig.run).and_then(|r| r.inline.as_ref()) else { continue };
let Some(sym) = f.doc.symbols.iter().find(|s| s.name == art.symbol) else { continue };
let Some(sym) = f.symbols.symbol(&art.symbol) else { continue };
// Strokes scale with the art (it is sized to the type, as in the SVG `<use>`).
let (node, kept) = self.placed_art(&sym.art, t.xf * ig.xf * f.doc.symbol_natural_xf(&art.symbol), true, None);
self.draw_placed_art(ctx, f, &node, kept);
+70
View File
@@ -314,6 +314,76 @@ fn past_the_measured_placements_an_instance_is_culled_by_an_estimate_of_its_art_
assert!(img.pixel(3, 20)[3] > 0, "{:?}", img.pixel(3, 20));
}
/// 2,000 symbols, then two named "Mark" (a red square, then a blue one), and an instance of
/// "Mark" at (25, 25) and one with a drop shadow at (70, 70). With `second` the blue square's
/// symbol is named that instead.
fn marks(second: &str) -> Document {
let mut d = Document::new(100.0, 100.0);
for i in 0..2000 {
let art = rect_node(&mut d, Rect::new(0.0, 0.0, 1.0, 1.0), Paint::solid(Color::BLACK), Paint::None, 0.0);
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: format!("Filler {i}"), art: Arc::new(art) });
}
for (name, color) in [("Mark", Color::rgb(1.0, 0.0, 0.0)), (second, Color::rgb(0.0, 0.0, 1.0))] {
let art = rect_node(&mut d, Rect::new(-10.0, -10.0, 10.0, 10.0), Paint::solid(color), Paint::None, 0.0);
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: name.into(), art: Arc::new(art) });
}
let l = d.layers[0].id;
let plain = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Mark".into(), xf: Affine::translate((25.0, 25.0)) });
let mut shadowed = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Mark".into(), xf: Affine::translate((70.0, 70.0)) });
shadowed.appearance.effects.push(vectorcraft_doc::Effect {
id: "stylize.dropShadow".into(),
params: serde_json::json!({"x": 4, "y": 4, "blur": 0}),
visible: true,
});
d.insert(Some(l), 0, plain).unwrap();
d.insert(Some(l), 1, shadowed).unwrap();
d
}
/// Instances among many symbols draw the first symbol of their name, the same pixels as when no
/// other symbol has that name.
#[test]
fn instances_draw_the_first_symbol_of_their_name() {
let img = render(&marks("Mark"));
assert_eq!(img.pixel(25, 25), [255, 0, 0, 255]);
assert_eq!(img.pixel(70, 70), [255, 0, 0, 255]);
assert!(img.pixels == render(&marks("Other")).pixels, "the pixels differ");
}
/// A frame that draws 300 instances with drop shadows, among 2,000 symbols, and an envelope around
/// instances reads the symbol list once to find their symbols.
#[test]
fn a_frame_reads_the_symbol_list_once() {
let mut d = marks("Other");
let l = d.layers[0].id;
for i in 0..300 {
let xf = Affine::translate((f64::from(i % 20) * 5.0, f64::from(i / 20) * 5.0)) * Affine::scale(0.2);
let mut n = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Mark".into(), xf });
n.appearance.effects.push(vectorcraft_doc::Effect {
id: "stylize.dropShadow".into(),
params: serde_json::json!({"x": 1, "y": 1, "blur": 0}),
visible: true,
});
d.insert(Some(l), usize::MAX, n).unwrap();
}
let content = Arc::new(Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Mark".into(), xf: Affine::translate((50.0, 50.0)) }));
let kind = vectorcraft_doc::live::EnvelopeKind::Warp { style: "arc".into(), bend: 30.0, h: 0.0, v: 0.0, horizontal: true, version: 0 };
let envelope = NodeKind::Envelope {
content: vec![content],
kind: Box::new(kind),
fidelity: 50.0,
editing: false,
options: Default::default(),
frame: Box::new(Affine::IDENTITY),
};
let envelope = Node::new(d.alloc_id(), envelope);
d.insert(Some(l), usize::MAX, envelope).unwrap();
let before = vectorcraft_doc::symbols_read();
render(&d);
let read = vectorcraft_doc::symbols_read() - before;
assert!(read <= d.symbols.len(), "{read} symbols read, {} in the document", d.symbols.len());
}
/// Symbols 0 to 29 each hold two instances of the next, sheared two ways, so that the 2^30
/// instances drawn from the first are all placed differently. Symbol 30 holds a square with a drop
/// shadow. An instance of symbol 0 lies far left of the view. With `effect`, every instance has
+3 -2
View File
@@ -1241,9 +1241,10 @@ fn symbol_instances_with_effects_are_charged_to_the_symbol_budget() {
let inst = d.layers[0].children().unwrap()[0].clone();
let mut r = Renderer::new();
r.symbol_nodes = vectorcraft_doc::MAX_SYMBOL_NODES - 1;
assert!(r.charge_fx_instance(&d, &inst), "one object fits");
let symbols = d.symbol_boxes();
assert!(r.charge_fx_instance(&symbols, &inst), "one object fits");
assert_eq!(r.symbol_nodes, vectorcraft_doc::MAX_SYMBOL_NODES);
assert!(!r.charge_fx_instance(&d, &inst), "the next does not");
assert!(!r.charge_fx_instance(&symbols, &inst), "the next does not");
assert_eq!(r.symbol_nodes, vectorcraft_doc::MAX_SYMBOL_NODES);
}
+16
View File
@@ -463,3 +463,19 @@ fn backdrop_drag_perf() {
);
}
}
/// A gradient mesh far larger than any buffer (a damaged file can give one) is drawn without
/// flattening its whole outline in device pixels, which would make more segments than memory holds.
#[test]
fn a_mesh_past_any_buffer_draws_without_flattening_its_outline() {
let side = 1e30;
let mut d = Document::new(595.0, 842.0);
let m = vectorcraft_doc::GradientMesh::from_surface(2, 2, &|u, v| vectorcraft_geom::Point::new(u * side, v * side + u * u * side), &|u, v| {
Color::rgb(u as f32, v as f32, 0.5)
});
let layer = d.layers[0].id;
let node = Node::new(d.alloc_id(), NodeKind::Mesh(m));
d.insert(Some(layer), 0, node).unwrap();
let image = Renderer::new().render(&d, 640, 900, view(1.0, (640, 900)), &RenderOptions::default());
assert_eq!(image.pixels.len(), 640 * 900 * 4);
}
+2
View File
@@ -47,3 +47,5 @@ vectorcraft-text = { workspace = true, features = ["test-fonts"] }
craft-svg = { workspace = true, features = ["tree-render", "tree-text"] }
vectorcraft-testkit = { workspace = true }
proptest = { workspace = true }
# How many times the symbol list is read to find symbols by name.
vectorcraft-doc = { workspace = true, features = ["symbol-read-count"] }
+4
View File
@@ -117,6 +117,7 @@ fn write(doc: &Document, opts: &ExportOptions, native: Option<&[u8]>, id_prefix:
linked: Vec::new(),
instance_xf: Affine::IDENTITY,
symbols: HashMap::new(),
symbol_lookup: doc.symbol_boxes(),
symbol_nest: 0,
symbol_nodes: 0,
inline_graphic: false,
@@ -301,6 +302,9 @@ struct Writer<'a> {
instance_xf: Affine,
/// What each symbol's instances can share, by symbol name (see [`Writer::symbol_use`]).
symbols: HashMap<String, SymbolDef>,
/// The document's symbols, found by name ([`vectorcraft_doc::SymbolBoxes::symbol`]) in time
/// independent of how many symbols the document holds.
symbol_lookup: vectorcraft_doc::SymbolBoxes<'a>,
/// Symbols being written inside one another (instances nested deeper are left out: a symbol
/// can't contain itself).
symbol_nest: u32,
+16 -14
View File
@@ -51,15 +51,16 @@ fn export_shape_bounds(n: &Node) -> Option<Rect> {
impl Reuse {
const NONE: Self = Self { moves: false, turns: false, scales: false };
/// What a def of symbol art `art` stands for.
pub(crate) fn of(doc: &Document, art: &Node) -> Self {
/// What a def of symbol art `art` stands for, in `doc`. `find` finds the symbol of each
/// instance in it by name.
pub(crate) fn of<'d>(doc: &'d Document, find: &dyn Fn(&str) -> Option<&'d vectorcraft_doc::Symbol>, art: &Node) -> Self {
let mut r = Self { moves: true, turns: true, scales: true };
r.scan(doc, art, 0);
r.scan(doc, find, art, 0);
r
}
/// Narrow down to what `n` (inside symbols nested `depth` deep) allows.
fn scan(&mut self, doc: &Document, n: &Node, depth: u32) {
fn scan<'d>(&mut self, doc: &'d Document, find: &dyn Fn(&str) -> Option<&'d vectorcraft_doc::Symbol>, n: &Node, depth: u32) {
let pattern = |p: &Paint| matches!(p, Paint::Pattern { .. });
let text_patterns = matches!(&n.kind, NodeKind::Text(t) if t.runs.iter().any(|r| pattern(&r.style.fill) || pattern(&r.style.stroke)));
let unlinked_mask = n.extras().mask.as_ref().is_some_and(|m| !m.linked);
@@ -95,17 +96,17 @@ impl Reuse {
if doc.symbol_nine_slice(symbol).is_some() {
self.scales = false;
}
if let Some(s) = doc.symbols.iter().find(|s| s.name == *symbol) {
self.scan(doc, &s.art, depth + 1);
if let Some(s) = find(symbol) {
self.scan(doc, find, &s.art, depth + 1);
}
}
_ => {}
}
if let Some(m) = &n.extras().mask {
self.scan(doc, &m.art, depth);
self.scan(doc, find, &m.art, depth);
}
for c in n.children().into_iter().flatten() {
self.scan(doc, c, depth);
self.scan(doc, find, c, depth);
}
}
@@ -481,7 +482,7 @@ impl Writer<'_> {
if let NodeKind::SymbolInstance { symbol, .. } = &n.kind {
let custom = !n.extras().symbol_overrides.is_empty();
if symbols.insert((symbol.clone(), custom.then_some(n.id)))
&& let Some(s) = self.doc.symbols.iter().find(|s| s.name == *symbol)
&& let Some(s) = self.symbol_lookup.symbol(symbol)
{
stack.push(if custom { std::sync::Arc::new(vectorcraft_brush::instance_art(&s.art, n)) } else { s.art.clone() });
}
@@ -518,7 +519,7 @@ impl Writer<'_> {
/// its geometry, so the region also covers the geometry's box, placed, grown by the strokes'
/// and effects' reach unscaled.
fn region_attrs(&mut self, nodes: &[&Node]) -> String {
let symbols = self.region_boxes.take().unwrap_or_else(|| self.doc.symbol_boxes());
let symbols = self.region_boxes.take().unwrap_or_else(|| self.symbol_lookup.unmeasured());
let mut art_reach = std::mem::take(&mut self.art_reach);
let region = self.region_of(&symbols, &mut art_reach, nodes);
self.region_boxes = Some(symbols);
@@ -528,7 +529,7 @@ impl Writer<'_> {
/// The box of what each of `nodes` paints, as [`Self::paint_box`] measures it.
fn paint_boxes(&mut self, nodes: &[&Node]) -> Vec<Option<Option<Rect>>> {
let symbols = self.region_boxes.take().unwrap_or_else(|| self.doc.symbol_boxes());
let symbols = self.region_boxes.take().unwrap_or_else(|| self.symbol_lookup.unmeasured());
let mut art_reach = std::mem::take(&mut self.art_reach);
let boxes = nodes.iter().map(|n| self.paint_box(&symbols, &mut art_reach, n)).collect();
self.region_boxes = Some(symbols);
@@ -615,7 +616,7 @@ impl Writer<'_> {
return Some(own + past + self.paint_reach(symbols, art_reach, &g, gb, depth + 1)?);
}
let symbol = match &n.kind {
NodeKind::SymbolInstance { symbol, xf } => self.doc.symbols.iter().find(|s| s.name == *symbol).map(|s| (s, xf)),
NodeKind::SymbolInstance { symbol, xf } => self.symbol_lookup.symbol(symbol).map(|s| (s, xf)),
_ => None,
};
if n.children().is_none_or(|c| c.is_empty()) && symbol.is_none() {
@@ -1026,7 +1027,7 @@ impl Writer<'_> {
let doc = self.doc;
// The instances nested in an inline graphic's art are ordinary instances again.
let inline = std::mem::take(&mut self.inline_graphic);
let Some(sym) = doc.symbols.iter().find(|s| s.name == *symbol) else { return };
let Some(sym) = self.symbol_lookup.symbol(symbol) else { return };
if self.symbol_nest > MAX_SYMBOL_NEST {
return;
}
@@ -1113,7 +1114,8 @@ impl Writer<'_> {
return None;
}
if !self.symbols.contains_key(&sym.name) {
let reuse = Reuse::of(self.doc, &sym.art);
let lookup = &self.symbol_lookup;
let reuse = Reuse::of(self.doc, &|name| lookup.symbol(name), &sym.art);
self.symbols.insert(sym.name.clone(), SymbolDef { id: None, reuse, nodes: 0 });
}
let def = self.symbols.get(&sym.name)?;
+2 -2
View File
@@ -680,7 +680,7 @@ impl Writer<'_> {
}
return 0;
}
let bounds = n.visual_bounds_with(&self.doc.symbol_boxes());
let bounds = n.visual_bounds_with(&self.symbol_lookup.unmeasured());
// An Outer Glow's silhouette grows by a quarter of a pixel of the document's raster grid first.
let grow = 18.0 / self.doc.raster_ppi();
let reach: f64 =
@@ -705,7 +705,7 @@ impl Writer<'_> {
// object's geometry turned into it, grown by what its strokes and other paint add
// around it in the document: a square that far to each side, as it measures in
// user space along each axis (a miter corner reaches that far along both).
let symbols = self.doc.symbol_boxes();
let symbols = self.symbol_lookup.unmeasured();
let visual = input.visual_bounds_with(&symbols).unwrap_or_default();
let user_box = if sf.moves_only() {
visual - sf.origin()
+3 -3
View File
@@ -202,7 +202,7 @@ pub(crate) fn import_finding(
hidden: found.hidden,
uses: found.uses,
symbols: HashMap::new(),
symbol_names: HashSet::new(),
symbol_names: HashMap::new(),
symbol_suffixes: HashMap::new(),
pattern_suffixes: HashMap::new(),
blends: fx::blends(&xml, &scan.markers),
@@ -360,8 +360,8 @@ struct Importer {
uses: HashMap<String, String>,
/// The symbols made so far, by `<symbol>` id.
symbols: HashMap<String, SymbolMade>,
/// The names of the symbols made so far.
symbol_names: HashSet<String>,
/// The names of the symbols made so far, each with its index in the document's symbols.
symbol_names: HashMap<String, usize>,
/// Where the suffixes of each symbol and pattern name base go on from (`unique_name`).
symbol_suffixes: HashMap<String, usize>,
pattern_suffixes: HashMap<String, usize>,
+6 -4
View File
@@ -207,9 +207,11 @@ impl Importer {
None => {
let base = self.name_of(&sym).to_string();
let names = &self.symbol_names;
let name = unique_name(&base, &mut self.symbol_suffixes, |n| names.contains(n));
self.symbol_names.insert(name.clone());
let reuse = Reuse::of(&self.doc, &art);
let name = unique_name(&base, &mut self.symbol_suffixes, |n| names.contains_key(n));
let doc = &self.doc;
let find = |n: &str| names.get(n).and_then(|&i| doc.symbols.get(i)).filter(|s| s.name == n);
let reuse = Reuse::of(doc, &find, &art);
self.symbol_names.insert(name.clone(), self.doc.symbols.len());
let made = SymbolMade { name: name.clone(), art: without_ids(&art), reuse };
self.doc.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: name.clone(), art: Arc::new(art) });
self.symbols.insert(sym, made);
@@ -862,7 +864,7 @@ mod tests {
hidden: HashSet::new(),
uses: HashMap::new(),
symbols: HashMap::new(),
symbol_names: HashSet::new(),
symbol_names: HashMap::new(),
symbol_suffixes: HashMap::new(),
pattern_suffixes: HashMap::new(),
blends: HashMap::new(),
+58
View File
@@ -69,6 +69,64 @@ fn three_instances_give_one_symbol_and_three_uses() {
assert!(boxes.iter().any(|b| (b.x0 - 90.0).abs() < 1e-3 && (b.y0 - 30.0).abs() < 1e-3), "{boxes:?}");
}
/// 2,000 symbols, then two named "Mark" (a red square with a black stroke, then a blue one) and
/// "Holder", holding an instance of "Mark". Instances: "Mark" moved, "Mark" stretched (written as
/// its own art) and "Holder". With `second` the blue square's symbol is named that instead.
fn marks(second: &str) -> Document {
let mut d = Document::new(200.0, 120.0);
for i in 0..2000 {
let art = Node::path(
d.alloc_id(),
shapes::rectangle(Rect::new(0.0, 0.0, 1.0, 1.0)),
Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0),
);
d.symbols.push(Symbol { dynamic: false, name: format!("Filler {i}"), art: Arc::new(art) });
}
for (name, color) in [("Mark", Color::rgb8(255, 0, 0)), (second, Color::rgb8(0, 0, 255))] {
let ap = Appearance::basic(Paint::solid(color), Paint::solid(Color::BLACK), 2.0);
let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(-10.0, -10.0, 10.0, 10.0)), ap);
d.symbols.push(Symbol { dynamic: false, name: name.into(), art: Arc::new(art) });
}
let held = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Mark".into(), xf: Affine::translate((5.0, 5.0)) });
let holder = Node::group(d.alloc_id(), vec![Arc::new(held)]);
d.symbols.push(Symbol { dynamic: false, name: "Holder".into(), art: Arc::new(holder) });
instance(&mut d, "Mark", Affine::translate((25.0, 25.0)));
instance(&mut d, "Mark", Affine::translate((80.0, 60.0)) * Affine::scale_non_uniform(2.0, 1.0));
instance(&mut d, "Holder", Affine::translate((150.0, 60.0)));
d
}
/// Instances among many symbols are written with the first symbol of their name, the same SVG as
/// when no other symbol has that name.
#[test]
fn instances_are_written_with_the_first_symbol_of_their_name() {
let svg = export(&marks("Mark"), &ExportOptions::default());
assert_eq!(svg, export(&marks("Other"), &ExportOptions::default()));
assert!(svg.contains("#ff0000") && !svg.contains("#0000ff"), "{svg}");
}
/// An export of 300 instances with drop shadows, among 2,000 symbols, reads the symbol list once
/// to find their symbols.
#[test]
fn an_export_reads_the_symbol_list_once() {
let mut d = marks("Other");
for i in 0..300 {
let xf = Affine::translate((f64::from(i % 20) * 10.0, f64::from(i / 20) * 8.0)) * Affine::scale(0.2);
let mut n = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Mark".into(), xf });
n.appearance.effects.push(vectorcraft_doc::Effect {
id: "stylize.dropShadow".into(),
params: serde_json::json!({"x": 1, "y": 1, "blur": 0}),
visible: true,
});
let l = d.layers[0].id;
d.insert(Some(l), usize::MAX, n).unwrap();
}
let before = vectorcraft_doc::symbols_read();
export(&d, &ExportOptions::default());
let read = vectorcraft_doc::symbols_read() - before;
assert!(read <= d.symbols.len(), "{read} symbols read, {} in the document", d.symbols.len());
}
/// A scaled instance of a symbol with 9-slice guides is written as the canvas draws it, with no
/// `<use>`: at 200 × 150 its 10 × 10 corner square stays 10 × 10 and its center square becomes
/// 30 × 20. An instance at the natural size still uses the def.
+6
View File
@@ -28,6 +28,12 @@ icu_segmenter = "2.3"
# Grapheme clusters (a Thai consonant with its vowel and tone marks, an accented letter, an emoji
# sequence) for caret movement; MIT OR Apache-2.0, already in the build.
unicode-segmentation = "1.13"
# Hyphenation patterns and rules for German, Polish, Portuguese, Italian, Bulgarian, Turkish and
# Russian; MIT OR Apache-2.0, already in the build through the engine's spell checking.
craft-proof = { workspace = true }
# Composes a decomposed Cyrillic word (`и` + U+0306 is `й`) before its script check; MIT OR
# Apache-2.0, already in the build through craft-proof.
unicode-normalization = "0.1.26"
# Draws COLR colour glyphs whose paints documents have no form for (sweep gradients, compositing
# modes) into images: the canvas's renderer, already in the build.
vello_cpu = { workspace = true }

Some files were not shown because too many files have changed in this diff Show More