;;; TORVA LISP - Section Flatten (torva.kr/lisp.html)
;;; FLT : select a tilted 3D section (lines, arcs, polylines lying in one plane, e.g. a section exported
;;;       from a 3D analysis model) -> laid onto the XY plane (Z = 0), true size and shape kept
;;; Pick two points of a reference edge to make it horizontal, or Enter = the longest side of the
;;; smallest bounding box becomes horizontal (section stays at its centre X, Y)
;;; Objects on locked layers are not selected. One U restores everything

(vl-load-com)

(defun tv-flt-cross (a b)
  (list (- (* (cadr a) (caddr b)) (* (caddr a) (cadr b)))
        (- (* (caddr a) (car b)) (* (car a) (caddr b)))
        (- (* (car a) (cadr b)) (* (cadr a) (car b)))))
(defun tv-flt-len (v) (sqrt (+ (* (car v) (car v)) (* (cadr v) (cadr v)) (* (caddr v) (caddr v)))))
(defun tv-flt-dot (a b) (+ (* (car a) (car b)) (* (cadr a) (cadr b)) (* (caddr a) (caddr b))))
(defun tv-flt-scl (v k) (mapcar '(lambda (x) (* x k)) v))
(defun tv-flt-unit (v / l) (setq l (tv-flt-len v)) (if (> l 1e-12) (tv-flt-scl v (/ 1.0 l))))

;; bounding box of 2D points rotated by th -> (area width height)
(defun tv-flt-box (p2d th / c s amin amax bmin bmax x y)
  (setq c (cos th) s (sin th) amin 1e99 amax -1e99 bmin 1e99 bmax -1e99)
  (foreach q p2d
    (setq x (+ (* (car q) c) (* (cadr q) s)) y (- (* (cadr q) c) (* (car q) s)))
    (setq amin (min amin x) amax (max amax x) bmin (min bmin y) bmax (max bmax y)))
  (list (* (- amax amin) (- bmax bmin)) (- amax amin) (- bmax bmin)))

;; curve end points of the selection (WCS)
(defun tv-flt-points (ss / i e sp ep pts)
  (setq i 0)
  (repeat (sslength ss)
    (setq e (ssname ss i) i (1+ i)
          sp (vl-catch-all-apply 'vlax-curve-getStartPoint (list e))
          ep (vl-catch-all-apply 'vlax-curve-getEndPoint (list e)))
    (if (and (listp sp) (listp ep) (= (length sp) 3) (= (length ep) 3))
      (setq pts (cons sp (cons ep pts)))))
  pts)

(defun c:FLT (/ *error* old doc ce ss pts p1 p2 p3 d dmax nrm e1 e2 cen p2d best bth th tend res
                c2 s2 eH eV a amin amax R pa pb s1 s2p s3 d1 d2 d3 auto)
  (setq old *error* doc (vla-get-ActiveDocument (vlax-get-acad-object)) ce (getvar "CMDECHO"))
  (defun *error* (msg)
    (if (/= (getvar "CMDACTIVE") 0) (command))
    (setvar "CMDECHO" ce)
    (vla-EndUndoMark doc)
    (setq *error* old)
    (if (and msg (not (wcmatch (strcase msg) "*CANCEL*,*QUIT*,*BREAK*"))) (princ (strcat "\nError: " msg)))
    (princ))
  (princ "\n눕힐 단면 선택: ")
  (cond
    ((null (setq ss (ssget "_:L"))))
    ((< (length (setq pts (tv-flt-points ss))) 3) (princ "\nNeed lines, arcs or polylines"))
    (T
     ;; plane normal from three widely spread points
     (setq p1 (car pts) dmax -1.0)
     (foreach q pts (if (> (setq d (distance p1 q)) dmax) (setq dmax d p2 q)))
     (setq e1 (mapcar '- p2 p1) dmax -1.0)
     (foreach q pts
       (if (> (setq d (tv-flt-len (tv-flt-cross e1 (mapcar '- q p1)))) dmax) (setq dmax d p3 q)))
     (setq nrm (tv-flt-unit (tv-flt-cross e1 (mapcar '- p3 p1))))
     (if (or (null nrm) (< (distance p1 p2) 1e-8))
       (princ "\nObjects lie on one line - plane not found")
       (progn
         (setq e1 (tv-flt-unit e1) e2 (tv-flt-unit (tv-flt-cross nrm e1))
               cen (tv-flt-scl (apply 'mapcar (cons '+ pts)) (/ 1.0 (length pts))))
         (if (setq pa (getpoint "\n수평 기준 첫 점 <자동>: "))
           (setq pb (getpoint pa "\n두 번째 점: ")))
         (if (and pa pb (> (distance pa pb) 1e-8))
           ;; picked edge -> horizontal, its first point keeps X, Y
           (setq pa (trans pa 1 0) pb (trans pb 1 0)
                 eH (tv-flt-unit (mapcar '- pb pa)) eV (tv-flt-unit (tv-flt-cross nrm eH))
                 R (distance pa pb) s1 pa
                 d1 (list (car pa) (cadr pa) 0.0))
           ;; Enter -> longest side of the smallest bounding box horizontal
           (progn
             (setq auto T
                   p2d (mapcar '(lambda (q) (list (tv-flt-dot (mapcar '- q cen) e1) (tv-flt-dot (mapcar '- q cen) e2))) pts)
                   best 1e99 bth 0.0 th 0.0)
             (while (< th pi)
               (if (< (car (setq res (tv-flt-box p2d th))) best) (setq best (car res) bth th))
               (setq th (+ th (/ pi 180.0))))
             (setq th (- bth (/ pi 180.0)) tend (+ bth (/ pi 180.0)))
             (while (<= th tend)
               (if (< (car (setq res (tv-flt-box p2d th))) best) (setq best (car res) bth th))
               (setq th (+ th (/ pi 1800.0))))
             (setq c2 (cos bth) s2 (sin bth) res (tv-flt-box p2d bth)
                   eH (if (>= (cadr res) (caddr res))
                        (mapcar '+ (tv-flt-scl e1 c2) (tv-flt-scl e2 s2))
                        (mapcar '+ (tv-flt-scl e1 (- s2)) (tv-flt-scl e2 c2)))
                   eH (tv-flt-unit eH) eV (tv-flt-unit (tv-flt-cross nrm eH)) amin 1e99 amax -1e99)
             (foreach q pts (setq a (tv-flt-dot (mapcar '- q cen) eH) amin (min amin a) amax (max amax a)))
             (setq R (max (- amax amin) 1.0) s1 cen d1 (list (car cen) (cadr cen) 0.0))))
         (setq s2p (mapcar '+ s1 (tv-flt-scl eH R)) s3 (mapcar '+ s1 (tv-flt-scl eV R))
               d2 (list (+ (car d1) R) (cadr d1) 0.0) d3 (list (car d1) (+ (cadr d1) R) 0.0))
         (vla-StartUndoMark doc)
         (setvar "CMDECHO" 0)
         (command "_.ALIGN" ss "" "_non" (trans s1 0 1) "_non" (trans d1 0 1)
                  "_non" (trans s2p 0 1) "_non" (trans d2 0 1) "_non" (trans s3 0 1) "_non" (trans d3 0 1))
         (while (/= (getvar "CMDACTIVE") 0) (command ""))
         (setvar "CMDECHO" ce)
         (vla-EndUndoMark doc)
         (princ (strcat "\n" (itoa (sslength ss)) " object(s) flattened ("
                        (if auto "longest side horizontal" "picked edge horizontal") ")"))))))
  (setq *error* old)
  (princ)
)

(princ "\nTORVA Section Flatten: FLT | torva.kr")
(princ)

;;; ---- TVKEY: change a shortcut - shared by every TORVA LISP (torva.kr/lisp.html) ----
;;; TVKEY -> command -> new shortcut. The original command keeps working
;;; Shortcuts are saved on this PC as TORVA-KEYS and restored whenever a TORVA LISP loads
;;; (Every TORVA LISP carries this block; loading several just redefines the same functions)

;; "A1=PY;B2=CN;" -> (("A1" . "PY") ("B2" . "CN"))
(defun tv-key-list (/ s i out)
  (setq s (cond ((getenv "TORVA-KEYS")) ("")) out nil)
  (while (setq i (vl-string-search ";" s))
    (setq out (cons (substr s 1 i) out) s (substr s (+ i 2))))
  (if (/= s "") (setq out (cons s out)))
  (vl-remove nil
    (mapcar '(lambda (x / j) (if (setq j (vl-string-search "=" x)) (cons (substr x 1 j) (substr x (+ j 2)))))
            (reverse out))))

(defun tv-key-save (lst)
  (setenv "TORVA-KEYS" (apply 'strcat (mapcar '(lambda (p) (strcat (car p) "=" (cdr p) ";")) lst))))

;; is cmd a loaded LISP command
(defun tv-key-cmd-p (cmd)
  (member (type (eval (read (strcat "C:" cmd)))) '(SUBR USUBR EXRXSUBR)))

(defun tv-key-def (key cmd)
  (eval (list 'defun (read (strcat "C:" key)) '() (list (read (strcat "C:" cmd))) '(princ))))

;; is key an alias in acad.pgp ("L,   *LINE")
(defun tv-key-pgp-p (key / f h l hit)
  (if (setq f (findfile "acad.pgp"))
    (progn
      (setq h (open f "r"))
      (while (and (not hit) (setq l (read-line h)))
        (if (and (not (wcmatch l ";*")) (wcmatch (strcase l) (strcat key ",*"))) (setq hit T)))
      (close h)))
  hit)

;; reason the key cannot be used, nil if fine
(defun tv-key-bad (key lst)
  (cond
    ((not (vl-every '(lambda (c) (or (<= 48 c 57) (<= 65 c 90))) (vl-string->list key))) "영문·숫자만")
    ((getcname key) "AutoCAD 명령 이름")
    ((tv-key-pgp-p key) "acad.pgp 별칭과 같음")
    ((and (tv-key-cmd-p key) (not (assoc key lst))) "이미 있는 리습 명령")))

;; "My shortcuts" lines at the end of the file: (tv-my-key "A1" "BN"). Bad key -> reason only
(defun tv-my-key (key cmd / why)
  (setq key (strcase key) cmd (strcase cmd))
  (cond ((not (tv-key-cmd-p cmd)))
        ((setq why (tv-key-bad key (list (cons key cmd)))) (princ (strcat "\nShortcut " key ": " why)))
        (T (tv-key-def key cmd))))

(defun c:TVKEY (/ cmd key lst why)
  (setq lst (tv-key-list)
        cmd (strcase (getstring "\n단축키를 붙일 명령 [목록(?)]: ")))
  (cond
    ((= cmd ""))
    ((= cmd "?")
     (if lst
       (foreach p lst (princ (strcat "\n  " (car p) " = " (cdr p))))
       (princ "\nNo shortcuts set")))
    ((not (tv-key-cmd-p cmd)) (princ (strcat "\n" cmd " is not a loaded LISP command")))
    (T
     (setq key (strcase (getstring (strcat "\n" cmd " 의 새 단축키 [지우기(-)]: "))))
     (cond
       ((= key ""))
       ((= key "-")
        (foreach p lst
          (if (= (cdr p) cmd) (set (read (strcat "C:" (car p))) nil)))
        (tv-key-save (vl-remove-if '(lambda (p) (= (cdr p) cmd)) lst))
        (princ (strcat "\nShortcut for " cmd " removed")))
       ((= key cmd))
       ((setq why (tv-key-bad key lst)) (princ (strcat "\n" key ": " why)))
       (T
        (tv-key-save (cons (cons key cmd) (vl-remove-if '(lambda (p) (= (car p) key)) lst)))
        (tv-key-def key cmd)
        (princ (strcat "\n" key " now runs " cmd))))))
  (princ))

;; on load: restore saved shortcuts whose command is loaded
(foreach p (tv-key-list)
  (if (tv-key-cmd-p (cdr p)) (tv-key-def (car p) (cdr p))))
(princ "\nTVKEY: change a shortcut | torva.kr")
(princ)

;;; ---- My shortcuts: lines set at torva.kr download land below. Edit or add lines to change them ----
