;;; ---------------------------------------------------------------------
;;;  CWWIND-bgol.lsp
;;;  Command:  CWW
;;;
;;;  PURPOSE
;;;  Rebuilds a closed polygon so its vertices run CLOCKWISE, starting
;;;  from a user-specified point. Many survey/GIS systems require a
;;;  specific winding direction for boundary polygons; this routine
;;;  determines the current winding via the shoelace formula, reverses
;;;  it if needed, rotates the vertex list to start at the chosen point,
;;;  and creates a brand-new polyline in place of the original.
;;;
;;;  USAGE
;;;    1. Load this file (APPLOAD or drag-drop onto the drawing window).
;;;    2. Type   CWW   at the command line and press Enter.
;;;    3. Select a CLOSED polyline (the routine requires Closed = Yes).
;;;    4. Specify the desired starting point (nearest existing vertex is
;;;       used as the new start).
;;;    5. The original polyline is erased; a new one is created on layer
;;;       "BGOL-CWW" with vertices running clockwise from that point.
;;;
;;;  NOTES
;;;    - Winding direction is determined via the signed area (shoelace)
;;;      formula; in standard screen/plan coordinates a negative signed
;;;      area indicates clockwise winding.
;;;    - This is an original, independently written implementation.
;;;      It is INSPIRED by the general idea of polygon-winding
;;;      normalization utilities common in survey/GIS drafting
;;;      workflows, but the code, command name and file name here are
;;;      new 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)

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

(defun BGOL:CWW-GetVerts (obj / coords pts)
  (setq coords (vlax-safearray->list (vlax-variant-value (vlax-get obj 'Coordinates))))
  (setq pts '())
  (while coords
    (setq pts (append pts (list (list (car coords) (cadr coords)))))
    (setq coords (cddr coords))
  )
  pts
)

;; Signed area via shoelace formula; negative = clockwise (screen coords)
(defun BGOL:CWW-SignedArea (pts / n i sum p1 p2)
  (setq n (length pts))
  (setq sum 0.0)
  (setq i 0)
  (while (< i n)
    (setq p1 (nth i pts))
    (setq p2 (nth (rem (1+ i) n) pts))
    (setq sum (+ sum (- (* (car p1) (cadr p2)) (* (car p2) (cadr p1)))))
    (setq i (1+ i))
  )
  (/ sum 2.0)
)

;; Rotate list so element nearest to pt becomes first
(defun BGOL:CWW-RotateToNearest (pts pt / n i best bestd d rotated)
  (setq n (length pts))
  (setq best 0)
  (setq bestd (distance pt (nth 0 pts)))
  (setq i 1)
  (while (< i n)
    (setq d (distance pt (nth i pts)))
    (if (< d bestd) (progn (setq best i) (setq bestd d)))
    (setq i (1+ i))
  )
  (setq rotated '())
  (setq i 0)
  (while (< i n)
    (setq rotated (append rotated (list (nth (rem (+ best i) n) pts))))
    (setq i (1+ i))
  )
  rotated
)

(defun BGOL:CWW-MakePolyline (pointlist lname / dxfdata pt)
  (setq dxfdata (list '(0 . "LWPOLYLINE")
                       '(100 . "AcDbEntity")
                       (cons 8 lname)
                       '(100 . "AcDbPolyline")
                       (cons 90 (length pointlist))
                       '(70 . 1)  ; closed
                 )
  )
  (foreach pt pointlist
    (setq dxfdata (append dxfdata (list (cons 10 pt))))
  )
  (entmake dxfdata)
)

(defun C:CWW ( / ent edata flag obj verts area startpt final)
  (BGOL:CWW-EnsureLayer "BGOL-CWW")
  (setq ent (car (entsel "\nSelect closed polygon to recreate clockwise: ")))
  (if ent
    (progn
      (setq edata (entget ent))
      (setq flag (cdr (assoc 70 edata)))
      (if (/= 1 (logand 1 flag))
        (princ "\nSelected polyline is not closed (Closed flag = No). Aborting.")
        (progn
          (setq obj (vlax-ename->vla-object ent))
          (setq verts (BGOL:CWW-GetVerts obj))
          (setq area (BGOL:CWW-SignedArea verts))
          (if (> area 0.0) (setq verts (reverse verts)))
          (setq startpt (getpoint "\nSpecify starting point (nearest vertex will be used): "))
          (if startpt
            (setq final (BGOL:CWW-RotateToNearest verts startpt))
            (setq final verts)
          )
          (entdel ent)
          (BGOL:CWW-MakePolyline final "BGOL-CWW")
          (princ (strcat "\nCWW: polygon recreated clockwise with " (itoa (length final)) " vertex/vertices (BGOL-CWW)."))
        )
      )
    )
    (princ "\nNo polyline selected.")
  )
  (princ)
)

(princ "\nCWWIND-bgol.lsp loaded. Type CWW to recreate a closed polygon in clockwise winding order.")
(princ "\n  -- Free & open-source, courtesy of BGol Community (https://bgol.in/) --")
(princ)
