| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 17 | |
| 18 | |
| 19 | use std::path::{Path, PathBuf}; |
| 20 | use std::sync::{Arc, Mutex}; |
| 21 | |
| 22 | |
| 23 | pub const MAX_3D_SIZE: usize = 65; |
| 24 | |
| 25 | pub const MAX_1D_SIZE: usize = 65_536; |
| 26 | |
| 27 | const MAX_FILE_BYTES: u64 = 64 << 20; |
| 28 | |
| 29 | |
| 30 | #[derive(Debug, Clone, PartialEq)] |
| 31 | pub struct Cube { |
| 32 | |
| 33 | pub title: Option<String>, |
| 34 | |
| 35 | pub three_d: bool, |
| 36 | |
| 37 | pub size: usize, |
| 38 | |
| 39 | pub domain_min: [f32; 3], |
| 40 | |
| 41 | pub domain_max: [f32; 3], |
| 42 | |
| 43 | pub data: Vec<[f32; 3]>, |
| 44 | } |
| 45 | |
| 46 | fn nums<const N: usize>(rest: &[&str], line: usize, what: &str) -> Result<[f32; N], String> { |
| 47 | if rest.len() != N { |
| 48 | return Err(format!("line {line}: {what} wants {N} numbers, found {}", rest.len())); |
| 49 | } |
| 50 | let mut out = [0f32; N]; |
| 51 | for (o, t) in out.iter_mut().zip(rest) { |
| 52 | *o = t |
| 53 | .parse::<f32>() |
| 54 | .ok() |
| 55 | .filter(|v| v.is_finite()) |
| 56 | .ok_or_else(|| format!("line {line}: {what}: '{t}' is not a number"))?; |
| 57 | } |
| 58 | Ok(out) |
| 59 | } |
| 60 | |
| 61 | fn size_of(rest: &[&str], line: usize, what: &str, max: usize) -> Result<usize, String> { |
| 62 | let [t] = rest else { |
| 63 | return Err(format!("line {line}: {what} wants one size")); |
| 64 | }; |
| 65 | let n: usize = t.parse().map_err(|_| format!("line {line}: {what}: '{t}' is not a size"))?; |
| 66 | if !(2..=max).contains(&n) { |
| 67 | return Err(format!("line {line}: {what} {n} is outside 2..={max}")); |
| 68 | } |
| 69 | Ok(n) |
| 70 | } |
| 71 | |
| 72 | |
| 73 | |
| 74 | pub fn parse(text: &str) -> Result<Cube, String> { |
| 75 | let mut title = None; |
| 76 | let (mut size1, mut size3) = (None, None); |
| 77 | let (mut min, mut max) = ([0f32; 3], [1f32; 3]); |
| 78 | let mut data: Vec<[f32; 3]> = Vec::new(); |
| 79 | let mut want = 0usize; |
| 80 | for (i, raw) in text.lines().enumerate() { |
| 81 | let n = i + 1; |
| 82 | let line = raw.split('#').next().unwrap_or("").trim(); |
| 83 | if line.is_empty() { |
| 84 | continue; |
| 85 | } |
| 86 | let words: Vec<&str> = line.split_whitespace().collect(); |
| 87 | let head = words[0]; |
| 88 | let starts_alpha = head.starts_with(|c: char| c.is_ascii_alphabetic()); |
| 89 | if !starts_alpha { |
| 90 | if want == 0 { |
| 91 | return Err(format!("line {n}: table data before LUT_1D_SIZE or LUT_3D_SIZE")); |
| 92 | } |
| 93 | if data.len() == want { |
| 94 | return Err(format!("line {n}: more table entries than the declared {want}")); |
| 95 | } |
| 96 | data.push(nums::<3>(&words, n, "a table entry")?); |
| 97 | continue; |
| 98 | } |
| 99 | if !data.is_empty() { |
| 100 | return Err(format!("line {n}: keyword '{head}' after the table data began")); |
| 101 | } |
| 102 | let rest = &words[1..]; |
| 103 | match head { |
| 104 | "TITLE" => { |
| 105 | let t = line["TITLE".len()..].trim(); |
| 106 | title = Some(t.trim_matches('"').to_string()); |
| 107 | } |
| 108 | "LUT_1D_SIZE" => size1 = Some(size_of(rest, n, head, MAX_1D_SIZE)?), |
| 109 | "LUT_3D_SIZE" => size3 = Some(size_of(rest, n, head, MAX_3D_SIZE)?), |
| 110 | "DOMAIN_MIN" => min = nums::<3>(rest, n, head)?, |
| 111 | "DOMAIN_MAX" => max = nums::<3>(rest, n, head)?, |
| 112 | "LUT_1D_INPUT_RANGE" | "LUT_3D_INPUT_RANGE" => { |
| 113 | let [lo, hi] = nums::<2>(rest, n, head)?; |
| 114 | min = [lo; 3]; |
| 115 | max = [hi; 3]; |
| 116 | } |
| 117 | |
| 118 | |
| 119 | _ => {} |
| 120 | } |
| 121 | want = match (size1, size3) { |
| 122 | (Some(_), Some(_)) => { |
| 123 | return Err(format!("line {n}: both LUT_1D_SIZE and LUT_3D_SIZE; one table per file")); |
| 124 | } |
| 125 | (Some(s), None) => s, |
| 126 | (None, Some(s)) => s * s * s, |
| 127 | (None, None) => 0, |
| 128 | }; |
| 129 | } |
| 130 | if want == 0 { |
| 131 | return Err("no LUT_1D_SIZE or LUT_3D_SIZE line: not a .cube table".into()); |
| 132 | } |
| 133 | if data.len() != want { |
| 134 | return Err(format!("the table has {} entries, the size line declares {want}", data.len())); |
| 135 | } |
| 136 | if (0..3).any(|c| min[c] >= max[c]) { |
| 137 | return Err("DOMAIN_MIN must be below DOMAIN_MAX on every channel".into()); |
| 138 | } |
| 139 | Ok(Cube { |
| 140 | title, |
| 141 | three_d: size3.is_some(), |
| 142 | size: size3.or(size1).unwrap_or(0), |
| 143 | domain_min: min, |
| 144 | domain_max: max, |
| 145 | data, |
| 146 | }) |
| 147 | } |
| 148 | |
| 149 | |
| 150 | pub fn load(path: &Path) -> Result<Cube, String> { |
| 151 | let meta = std::fs::metadata(path).map_err(|e| format!("cannot read {}: {e}", path.display()))?; |
| 152 | if meta.len() > MAX_FILE_BYTES { |
| 153 | return Err(format!("{} is {} bytes, more than a .cube table can be", path.display(), meta.len())); |
| 154 | } |
| 155 | let bytes = std::fs::read(path).map_err(|e| format!("cannot read {}: {e}", path.display()))?; |
| 156 | let text = String::from_utf8(bytes).map_err(|_| format!("{} is not a text file", path.display()))?; |
| 157 | parse(&text).map_err(|e| format!("{}: {e}", path.display())) |
| 158 | } |
| 159 | |
| 160 | impl Cube { |
| 161 | |
| 162 | |
| 163 | pub fn sample(&self, rgb: [f32; 3]) -> [f32; 3] { |
| 164 | let edge = (self.size - 1) as f32; |
| 165 | let mut p = [0f32; 3]; |
| 166 | for c in 0..3 { |
| 167 | let t = (rgb[c] - self.domain_min[c]) / (self.domain_max[c] - self.domain_min[c]); |
| 168 | p[c] = t.clamp(0.0, 1.0) * edge; |
| 169 | } |
| 170 | if !self.three_d { |
| 171 | let mut out = [0f32; 3]; |
| 172 | for c in 0..3 { |
| 173 | let i = (p[c] as usize).min(self.size - 2); |
| 174 | let d = p[c] - i as f32; |
| 175 | out[c] = self.data[i][c] * (1.0 - d) + self.data[i + 1][c] * d; |
| 176 | } |
| 177 | return out; |
| 178 | } |
| 179 | let s = self.size; |
| 180 | let i = [0, 1, 2].map(|c| (p[c] as usize).min(s - 2)); |
| 181 | let d = [0, 1, 2].map(|c| p[c] - i[c] as f32); |
| 182 | let at = |r: usize, g: usize, b: usize| self.data[(i[0] + r) + (i[1] + g) * s + (i[2] + b) * s * s]; |
| 183 | let c000 = at(0, 0, 0); |
| 184 | let c111 = at(1, 1, 1); |
| 185 | let (dr, dg, db) = (d[0], d[1], d[2]); |
| 186 | |
| 187 | |
| 188 | let (w, a, b) = if dr > dg { |
| 189 | if dg > db { |
| 190 | ([1.0 - dr, dr - dg, dg - db, db], at(1, 0, 0), at(1, 1, 0)) |
| 191 | } else if dr > db { |
| 192 | ([1.0 - dr, dr - db, db - dg, dg], at(1, 0, 0), at(1, 0, 1)) |
| 193 | } else { |
| 194 | ([1.0 - db, db - dr, dr - dg, dg], at(0, 0, 1), at(1, 0, 1)) |
| 195 | } |
| 196 | } else if db > dg { |
| 197 | ([1.0 - db, db - dg, dg - dr, dr], at(0, 0, 1), at(0, 1, 1)) |
| 198 | } else if db > dr { |
| 199 | ([1.0 - dg, dg - db, db - dr, dr], at(0, 1, 0), at(0, 1, 1)) |
| 200 | } else { |
| 201 | ([1.0 - dg, dg - dr, dr - db, db], at(0, 1, 0), at(1, 1, 0)) |
| 202 | }; |
| 203 | [0, 1, 2].map(|c| w[0] * c000[c] + w[1] * a[c] + w[2] * b[c] + w[3] * c111[c]) |
| 204 | } |
| 205 | } |
| 206 | |
| 207 | |
| 208 | |
| 209 | |
| 210 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] |
| 211 | pub struct LutRef(u32); |
| 212 | |
| 213 | struct Entry { |
| 214 | path: PathBuf, |
| 215 | table: Result<Arc<Cube>, String>, |
| 216 | } |
| 217 | |
| 218 | static TABLE: Mutex<Vec<Entry>> = Mutex::new(Vec::new()); |
| 219 | |
| 220 | fn table() -> std::sync::MutexGuard<'static, Vec<Entry>> { |
| 221 | TABLE.lock().unwrap_or_else(|e| e.into_inner()) |
| 222 | } |
| 223 | |
| 224 | impl LutRef { |
| 225 | |
| 226 | |
| 227 | |
| 228 | |
| 229 | pub fn open(path: &Path) -> Self { |
| 230 | let mut t = table(); |
| 231 | if let Some(i) = t.iter().position(|e| e.path == path) { |
| 232 | if t[i].table.is_err() { |
| 233 | t[i].table = load(path).map(Arc::new); |
| 234 | } |
| 235 | return Self(i as u32); |
| 236 | } |
| 237 | t.push(Entry { |
| 238 | path: path.to_path_buf(), |
| 239 | table: load(path).map(Arc::new), |
| 240 | }); |
| 241 | Self((t.len() - 1) as u32) |
| 242 | } |
| 243 | |
| 244 | |
| 245 | |
| 246 | pub fn reload(path: &Path) -> Self { |
| 247 | let r = Self::open(path); |
| 248 | let fresh = load(path).map(Arc::new); |
| 249 | table()[r.0 as usize].table = fresh; |
| 250 | r |
| 251 | } |
| 252 | |
| 253 | |
| 254 | pub fn path(self) -> PathBuf { |
| 255 | table().get(self.0 as usize).map(|e| e.path.clone()).unwrap_or_default() |
| 256 | } |
| 257 | |
| 258 | |
| 259 | pub fn table(self) -> Result<Arc<Cube>, String> { |
| 260 | match table().get(self.0 as usize) { |
| 261 | Some(e) => e.table.clone(), |
| 262 | None => Err("unknown LUT".into()), |
| 263 | } |
| 264 | } |
| 265 | |
| 266 | |
| 267 | pub fn problem(self) -> Option<String> { |
| 268 | self.table().err() |
| 269 | } |
| 270 | } |
| 271 | |
| 272 | #[cfg(test)] |
| 273 | mod tests { |
| 274 | use super::*; |
| 275 | |
| 276 | |
| 277 | pub(crate) fn cube_text(size: usize, f: impl Fn([f32; 3]) -> [f32; 3]) -> String { |
| 278 | let mut s = format!("TITLE \"t\"\nLUT_3D_SIZE {size}\n"); |
| 279 | let e = (size - 1) as f32; |
| 280 | for b in 0..size { |
| 281 | for g in 0..size { |
| 282 | for r in 0..size { |
| 283 | let o = f([r as f32 / e, g as f32 / e, b as f32 / e]); |
| 284 | s.push_str(&format!("{} {} {}\n", o[0], o[1], o[2])); |
| 285 | } |
| 286 | } |
| 287 | } |
| 288 | s |
| 289 | } |
| 290 | |
| 291 | #[test] |
| 292 | fn identity_3d_samples_back_its_input() { |
| 293 | for size in [2, 17, 33] { |
| 294 | let c = parse(&cube_text(size, |p| p)).expect("parses"); |
| 295 | assert!(c.three_d && c.size == size); |
| 296 | for p in [[0.0, 0.0, 0.0], [1.0, 1.0, 1.0], [0.3, 0.71, 0.02], [0.5, 0.25, 0.9]] { |
| 297 | let o = c.sample(p); |
| 298 | for k in 0..3 { |
| 299 | assert!((o[k] - p[k]).abs() < 1e-5, "{size} {p:?} -> {o:?}"); |
| 300 | } |
| 301 | } |
| 302 | } |
| 303 | } |
| 304 | |
| 305 | |
| 306 | |
| 307 | #[test] |
| 308 | fn tetrahedral_is_exact_for_linear_tables() { |
| 309 | let f = |p: [f32; 3]| [p[2], 0.5 * p[0] + 0.25 * p[1], 1.0 - p[1]]; |
| 310 | let c = parse(&cube_text(9, f)).expect("parses"); |
| 311 | for p in [[0.13, 0.77, 0.5], [0.9, 0.1, 0.45], [0.33, 0.33, 0.34]] { |
| 312 | let (o, w) = (c.sample(p), f(p)); |
| 313 | for k in 0..3 { |
| 314 | assert!((o[k] - w[k]).abs() < 1e-5, "{p:?}: {o:?} vs {w:?}"); |
| 315 | } |
| 316 | } |
| 317 | } |
| 318 | |
| 319 | #[test] |
| 320 | fn one_d_and_domain() { |
| 321 | let c = parse("LUT_1D_SIZE 3\nDOMAIN_MIN 0 0 0\nDOMAIN_MAX 2 2 2\n0 0 0\n0.5 0.25 1\n1 1 1\n").expect("1D"); |
| 322 | assert!(!c.three_d); |
| 323 | |
| 324 | assert_eq!(c.sample([1.0, 1.0, 1.0]), [0.5, 0.25, 1.0]); |
| 325 | let o = c.sample([0.5, 0.5, 0.5]); |
| 326 | assert!((o[0] - 0.25).abs() < 1e-6 && (o[2] - 0.5).abs() < 1e-6); |
| 327 | |
| 328 | assert_eq!(c.sample([-3.0, 9.0, 2.0]), [0.0, 1.0, 1.0]); |
| 329 | let r = parse("LUT_3D_INPUT_RANGE -0.5 1.5\nLUT_3D_SIZE 2\n0 0 0\n1 0 0\n0 1 0\n1 1 0\n0 0 1\n1 0 1\n0 1 1\n1 1 1\n").expect("range"); |
| 330 | assert_eq!((r.domain_min, r.domain_max), ([-0.5; 3], [1.5; 3])); |
| 331 | } |
| 332 | |
| 333 | |
| 334 | #[test] |
| 335 | fn malformed_files_are_refused_by_name() { |
| 336 | let ok = cube_text(2, |p| p); |
| 337 | let cases: Vec<(String, &str)> = vec![ |
| 338 | (String::new(), "no LUT_1D_SIZE"), |
| 339 | ("# only a comment\n".into(), "no LUT_1D_SIZE"), |
| 340 | ("0 0 0\nLUT_3D_SIZE 2\n".into(), "before LUT_1D_SIZE"), |
| 341 | ("LUT_3D_SIZE 66\n".into(), "outside 2..=65"), |
| 342 | ("LUT_3D_SIZE 1\n0 0 0\n".into(), "outside 2..=65"), |
| 343 | ("LUT_3D_SIZE x\n".into(), "not a size"), |
| 344 | ("LUT_3D_SIZE 2 3\n".into(), "one size"), |
| 345 | ("LUT_3D_SIZE 99999999999999999999\n".into(), "not a size"), |
| 346 | ("LUT_1D_SIZE 2\nLUT_3D_SIZE 2\n".into(), "both"), |
| 347 | ("LUT_1D_SIZE 2\n0 0 0\n".into(), "has 1 entries"), |
| 348 | ("LUT_1D_SIZE 2\n0 0 0\n1 1 1\n1 1 1\n".into(), "more table entries"), |
| 349 | ("LUT_1D_SIZE 2\n0 0\n1 1 1\n".into(), "wants 3 numbers"), |
| 350 | ("LUT_1D_SIZE 2\n0 nan 0\n1 1 1\n".into(), "not a number"), |
| 351 | ("LUT_1D_SIZE 2\n0 inf 0\n1 1 1\n".into(), "not a number"), |
| 352 | ("LUT_1D_SIZE 2\n0 0 0\nTITLE late\n1 1 1\n".into(), "after the table"), |
| 353 | ("DOMAIN_MIN 1 0 0\nDOMAIN_MAX 0 1 1\nLUT_1D_SIZE 2\n0 0 0\n1 1 1\n".into(), "below DOMAIN_MAX"), |
| 354 | ("DOMAIN_MIN 0 0\nLUT_1D_SIZE 2\n".into(), "wants 3 numbers"), |
| 355 | (ok[..ok.len() - 7].to_string(), "entries"), |
| 356 | ("\u{0}\u{1}\u{2}garbage\n".into(), "before LUT_1D_SIZE"), |
| 357 | ]; |
| 358 | for (text, want) in cases { |
| 359 | let e = parse(&text).expect_err(&text); |
| 360 | assert!(e.contains(want), "{text:?}: {e}"); |
| 361 | } |
| 362 | |
| 363 | let mut seed = 0x9e37_79b9u32; |
| 364 | for _ in 0..300 { |
| 365 | let mut s = String::from("LUT_3D_SIZE 2\n"); |
| 366 | for _ in 0..40 { |
| 367 | seed ^= seed << 13; |
| 368 | seed ^= seed >> 17; |
| 369 | seed ^= seed << 5; |
| 370 | s.push(b"0123456789 .-e\nLUT_ #x"[(seed % 22) as usize] as char); |
| 371 | } |
| 372 | let _ = parse(&s); |
| 373 | } |
| 374 | } |
| 375 | |
| 376 | #[test] |
| 377 | fn a_missing_file_is_a_handle_with_a_reason() { |
| 378 | let r = LutRef::open(Path::new("/nonexistent/edith/look.cube")); |
| 379 | assert!(r.problem().expect("missing").contains("cannot read")); |
| 380 | assert_eq!(r, LutRef::open(Path::new("/nonexistent/edith/look.cube")), "one handle per path"); |
| 381 | } |
| 382 | } |