#lang racket
(require gigls/unsafe)

;;; Procedure:
;;;   image-select-regular-polygon!
;;; Parameters:
;;;   image, an image
;;;   operation, one of REPLACE, ADD, SUBTRACT, and INTERSECT
;;;   x, a real number
;;;   y, a real number
;;;   sides, an integer
;;;   radius, a real number
;;;   theta, a real number
;;; Purpose:
;;;   Selects a regular polygon of sides sides, centered at (x,y), with
;;;   each point radius away from the center.
;;; Produces:
;;;   [Nothing; called for the side effect]
;;; Preconditions:
;;;   sides >= 3
;;;   Some portion of the selection is on the image
;;; Postconditions:
;;;   The image now contains the described selection.
;;; Ponderings:
;;;   It would probably make more sense to make the side-length a parameter,
;;;   but I'm too lazy to convert side-length to radius.  It's also easier
;;;   to stretch the regular polygon if we work with a radius.
(define image-select-regular-polygon!
  (lambda (image operation x y sides radius theta)
    (let ([delta-angle (/ (* 2 pi) sides)])
      (image-select-polygon! image operation
                             (map (lambda (i)
                                    (let ([angle (+ theta (* i delta-angle))])
                                      (cons (+ x (* radius (cos angle)))
                                            (+ y (* radius (sin angle))))))
                                  (iota sides))))))


; (example sides copies)
;    A silly example with image-select-regular-polygon!  Selects lots of
;    polygons of decreasing radius and draws them in different colors
(define example
  (let* ([min-radius 30]
         [max-radius 120]
         [delta-angle (/ pi 9)])
    (lambda (sides copies)
      (let ([image (image-show (image-new 200 200))]
            [delta-hue (/ 360 copies)]
            [delta-radius (/ (- max-radius min-radius) copies)])
        (context-set-brush! "2. Hardness 050" 5)
        (map (lambda (i)
               (image-select-regular-polygon! image REPLACE 
                                              100 100
                                              sides
                                              (- max-radius (* i delta-radius))
                                              (* i delta-angle))
               (context-set-fgcolor! (hsv->irgb (list (round (* i delta-hue)) 1 1)))
               (image-fill! image)
               (context-set-fgcolor! "black")
               (image-stroke! image))
             (iota copies))
        (image-select-nothing! image)
        (context-update-displays!)
        image))))
