regenerate Y from V as follows.
[elisp/munsell.git] / munsell-conv.el
1 (require 'munsell-data)
2
3 (defun munsell-lookup (color)
4   (cdr (assoc color munsell-color-alist)))
5
6 (put 'munsell-split 'lisp-indent-function 2)
7 (defmacro munsell-split (color-expr vars body &optional invalid-action)
8   (let ((color-var (make-symbol "_color"))
9         (hue-var (nth 0 vars))
10         (value-var (nth 1 vars))
11         (chroma-var (nth 2 vars)))
12     `(let ((,color-var ,color-expr))
13        (if (string-match "^N\\([0-9]+\\(\\.[0-9]*\\)?\\)\\|\\([0-9]+\\(\\.[0-9]*\\)?\\)\\(B\\|BG\\|G\\|GY\\|Y\\|YR\\|R\\|RP\\|P\\|PB\\)\\([0-9]+\\(\\.[0-9]*\\)?\\)/\\([0-9]+\\(\\.[0-9]*\\)?\\)$" ,color-var)
14            (let ((,hue-var
15                   (if (match-beginning 1)
16                       '(0 . "N")
17                     (cons (string-to-number (match-string 3 ,color-var))
18                           (match-string 5 ,color-var))))
19                  (,value-var
20                   (string-to-number
21                    (match-string (if (match-beginning 1) 1 6) ,color-var)))
22                  (,chroma-var
23                   (if (match-beginning 1)
24                       0
25                     (string-to-number (match-string 8 ,color-var)))))
26              ,body)
27          ,(or
28            invalid-action
29            `(error "invalid munsell color: %s" ,color-var))))))
30
31 (defun munsell-round (h v c hue-round value-round chroma-round)
32   (let ((c-rounded (* 2 (apply chroma-round c '(2)))))
33     (concat
34      (if (= c-rounded 0)
35          "N"
36        (let ((h2 (* 5 (apply hue-round (car h) '(2.5)))))
37          (concat
38           (int-to-string (ash h2 -1))
39           (unless (= (logand h2 1) 0) ".5")
40           (cdr h))))
41      (if (< v 0.9)
42          (concat "0." (int-to-string (* 2 (apply value-round v '(0.2)))))
43        (int-to-string (apply value-round v '(1))))
44      (if (= c-rounded 0)
45          ""
46        (concat "/" (int-to-string c-rounded))))))
47
48 (defun munsell-convert (color)
49   (munsell-split color (h v c)
50     (munsell-lookup (munsell-round h v c 'round 'round 'round))))
51
52 (provide 'munsell-conv)