;;; ---------------------------------------------------------------------
;;;  UTM2LL-bgol.lsp
;;;  Command:  U2LL
;;;
;;;  PURPOSE
;;;  A CAD-native equivalent of the "UTM to Lat/Long" bulk-conversion
;;;  web tool: picks (or types) UTM Easting/Northing coordinates
;;;  directly from the drawing, converts them to approximate
;;;  geographic Latitude/Longitude using standard UTM inverse-
;;;  projection formulas (WGS84 ellipsoid), and labels the point in
;;;  the drawing with its computed Lat/Long -- so survey points laid
;;;  out in a CAD drawing can be cross-referenced against Google Maps
;;;  /Google Earth-style coordinates without leaving CAD or using a
;;;  separate web service.
;;;
;;;  USAGE
;;;    1. Load this file (APPLOAD or drag-drop onto the drawing window).
;;;    2. Type   U2LL   at the command line and press Enter.
;;;    3. Select the point(s) to convert -- pick a point in the
;;;       drawing, or select existing TEXT/POINT entities.
;;;    4. Enter the UTM zone number and hemisphere.
;;;    5. A new TEXT label showing "Lat, Long" (decimal degrees) is
;;;       created next to each converted point, on layer "BGOL-U2LL".
;;;
;;;  NOTES
;;;    - Uses the standard WGS84 ellipsoid (a=6378137.0,
;;;      f=1/298.257223563) and a truncated-series inverse
;;;      Transverse Mercator formula -- accurate to a few metres,
;;;      suitable for labeling/cross-reference purposes.
;;;    - This is an original, independently written implementation.
;;;      It is INSPIRED by the general idea of UTM-to-LatLong
;;;      coordinate conversion utilities common in survey/GIS
;;;      workflows (typically distributed as web-based SaaS tools),
;;;      but the code, command name and file name here are new,
;;;      entirely AutoLISP-native, and are NOT copied from, nor
;;;      identical to, any specific third-party product.
;;;
;;;  ---------------------------------------------------------------------
;;;  Developed and shared for the CAD community by:  BGol Community
;;;  Community website:                              https://bgol.in/
;;;  License:  Open-source & free to use, modify, and share for all.
;;;            Provided "as is", without warranty of any kind.
;;;  ---------------------------------------------------------------------

(vl-load-com)

(setq *bgol-u2ll-a* 6378137.0)
(setq *bgol-u2ll-f* (/ 1.0 298.257223563))
(setq *bgol-u2ll-k0* 0.9996)

(defun BGOL:U2LL-EnsureLayer (lname / )
  (if (not (tblsearch "LAYER" lname))
    (entmake (list '(0 . "LAYER")
                   '(100 . "AcDbSymbolTableRecord")
                   '(100 . "AcDbLayerTableRecord")
                   (cons 2 lname)
                   '(70 . 0)
                   '(62 . 1)          ; red
                   '(6 . "Continuous")))
  )
)

(defun BGOL:U2LL-MakeText (pt txt height lname / dxfdata)
  (setq dxfdata (list '(0 . "TEXT")
                       '(100 . "AcDbEntity")
                       (cons 8 lname)
                       '(100 . "AcDbText")
                       (cons 10 pt)
                       (cons 40 height)
                       (cons 1 txt)
                 )
  )
  (entmake dxfdata)
)

;; Inverse UTM projection (WGS84), truncated series -- returns (lat . lon) in degrees.
(defun BGOL:U2LL-UtmToLatLon (easting northing zone hemi / a f k0
                                e2 e2p n M mu e1 phi1 c1 t1 n1 r1 d
                                lat lon x y falseE falseN)
  (setq a *bgol-u2ll-a*)
  (setq f *bgol-u2ll-f*)
  (setq k0 *bgol-u2ll-k0*)
  (setq e2 (- (* 2.0 f) (* f f)))
  (setq e2p (/ e2 (- 1.0 e2)))
  (setq falseE 500000.0)
  (setq falseN (if (= hemi "South") 10000000.0 0.0))
  (setq x (- easting falseE))
  (setq y (- northing falseN))
  (setq M (/ y k0))
  (setq n (/ (- a (* a (sqrt (- 1.0 e2)))) (+ a (* a (sqrt (- 1.0 e2))))))
  (setq mu (/ M (* a (- 1.0 (/ e2 4.0) (* 3.0 e2 e2 (/ 1.0 64.0)) (* 5.0 e2 e2 e2 (/ 1.0 256.0))))))
  (setq e1 (/ (- 1.0 (sqrt (- 1.0 e2))) (+ 1.0 (sqrt (- 1.0 e2)))))
  (setq phi1 (+ mu
                (* (- (/ (* 3.0 e1) 2.0) (/ (* 27.0 e1 e1 e1) 32.0)) (sin (* 2.0 mu)))
                (* (- (/ (* 21.0 e1 e1) 16.0) (/ (* 55.0 e1 e1 e1 e1) 32.0)) (sin (* 4.0 mu)))
                (* (/ (* 151.0 e1 e1 e1) 96.0) (sin (* 6.0 mu)))
             )
  )
  (setq c1 (* e2p (cos phi1) (cos phi1)))
  (setq t1 (* (tan phi1) (tan phi1)))
  (setq n1 (/ a (sqrt (- 1.0 (* e2 (sin phi1) (sin phi1))))))
  (setq r1 (/ (* a (- 1.0 e2)) (expt (- 1.0 (* e2 (sin phi1) (sin phi1))) 1.5)))
  (setq d (/ x (* n1 k0)))
  (setq lat (- phi1
               (* (/ (* n1 (tan phi1)) r1)
                  (- (/ (* d d) 2.0)
                     (* (/ 1.0 24.0) (+ 5.0 (* 3.0 t1) (* 10.0 c1) (* -4.0 c1 c1) (* -9.0 e2p)) d d d d)
                  )
               )
            )
  )
  (setq lon (/ (- d
                  (* (/ 1.0 6.0) (+ 1.0 (* 2.0 t1) c1) d d d)
               )
               (cos phi1)
            )
  )
  (setq lat (/ (* lat 180.0) pi))
  (setq lon (+ (/ (* lon 180.0) pi) (- (* 6.0 zone) 183.0)))
  (cons lat lon)
)

(defun C:U2LL ( / zone hemi pt height result lat lon lbl)
  (BGOL:U2LL-EnsureLayer "BGOL-U2LL")
  (setq zone (getint "\nUTM Zone number <43>: "))
  (if (not zone) (setq zone 43))
  (initget "North South")
  (setq hemi (getkword "\nHemisphere [North/South] <North>: "))
  (if (not hemi) (setq hemi "North"))
  (setq height (getreal "\nLabel text height <2.0>: "))
  (if (not height) (setq height 2.0))
  (setq pt (getpoint "\nPick UTM point to convert (Easting=X, Northing=Y): "))
  (if pt
    (progn
      (setq result (BGOL:U2LL-UtmToLatLon (car pt) (cadr pt) zone hemi))
      (setq lat (car result))
      (setq lon (cdr result))
      (setq lbl (strcat (rtos lat 2 6) ", " (rtos lon 2 6)))
      (BGOL:U2LL-MakeText (list (+ (car pt) (* height 1.5)) (cadr pt) 0.0) lbl height "BGOL-U2LL")
      (princ (strcat "\nU2LL: point converted -> Lat " (rtos lat 2 6) "  Lon " (rtos lon 2 6)
                     " (labeled on layer BGOL-U2LL)."))
    )
    (princ "\nNo point picked.")
  )
  (princ)
)

(princ "\nUTM2LL-bgol.lsp loaded. Type U2LL to convert a picked UTM point to Lat/Long and label it.")
(princ "\n  -- Free & open-source, courtesy of BGol Community (https://bgol.in/) --")
(princ)
