;;; TORVA LISP - Rebar Array (torva.kr/lisp.html)
;;; RBS : pick the first bar, pick the last bar -> copies fill the gap evenly
;;;       Number = total bars including both ends. S = max spacing (bars placed at or under it)
;;; Bars = any objects (circle, block, line). Centre of each selection = its bounding box centre
;;; Last spacing kept until the drawing is closed. One undo removes all copies

(vl-load-com)

(if (null *TV-RBS-SPC*) (setq *TV-RBS-SPC* 200.0))

;; bounding box centre of a selection set
(defun tv-rbs-center (ss / i mn mx lo hi)
  (setq i 0)
  (repeat (sslength ss)
    (if (not (vl-catch-all-error-p
               (vl-catch-all-apply 'vla-getboundingbox (list (vlax-ename->vla-object (ssname ss i)) 'mn 'mx))))
      (setq lo (cons (vlax-safearray->list mn) lo) hi (cons (vlax-safearray->list mx) hi)))
    (setq i (1+ i)))
  (if lo
    (list (/ (+ (apply 'min (mapcar 'car lo)) (apply 'max (mapcar 'car hi))) 2.0)
          (/ (+ (apply 'min (mapcar 'cadr lo)) (apply 'max (mapcar 'cadr hi))) 2.0)
          0.0)))

(defun c:RBS (/ *error* old doc ss1 ss2 p1 p2 dist ang v n spc i j o)
  (setq doc (vla-get-ActiveDocument (vlax-get-acad-object)) old *error*)
  (defun *error* (msg)
    (vla-EndUndoMark doc) (setq *error* old)
    (if (not (wcmatch (strcase msg) "*CANCEL*,*QUIT*,*BREAK*")) (princ (strcat "\nError: " msg)))
    (princ))
  (vla-StartUndoMark doc)
  (princ "\n첫 철근 선택: ")
  (if (and (setq ss1 (ssget))
           (setq p1 (tv-rbs-center ss1))
           (princ "\n마지막 철근 선택: ")
           (setq ss2 (ssget))
           (setq p2 (tv-rbs-center ss2))
           (> (setq dist (distance p1 p2)) 1e-6))
    (progn
      (setq ang (angle p1 p2))
      (initget 6 "S")
      (setq v (getreal (strcat "\n거리 " (rtos dist 2 0) " | 철근 개수 (양 끝 포함) [간격(S)]: ")))
      (cond
        ((= v "S")
         (initget 6)
         (if (setq v (getdist (strcat "\n최대 간격 <" (rtos *TV-RBS-SPC* 2 0) ">: "))) (setq *TV-RBS-SPC* v))
         (setq n (fix (+ (/ dist *TV-RBS-SPC*) 0.999999))))   ; spaces
        ((numberp v) (setq n (1- (fix v)))))                   ; spaces = bars - 1
      (if (and n (> n 1))
        (progn
          (setq spc (/ dist n) i 1)
          (repeat (1- n)
            (setq j 0)
            (repeat (sslength ss1)
              (setq o (vla-copy (vlax-ename->vla-object (ssname ss1 j))))
              (vla-move o (vlax-3d-point p1) (vlax-3d-point (polar p1 ang (* spc i))))
              (setq j (1+ j)))
            (setq i (1+ i)))
          (princ (strcat "\n" (itoa (1+ n)) " bars @ " (rtos spc 2 1))))
        (if n (princ "\nNothing to add")))))
  (vla-EndUndoMark doc)
  (setq *error* old)
  (princ)
)

(princ "\nTORVA Rebar Array: RBS | 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 ----
