Saturday, June 18, 2022

A circle is the limit of polygons

As the number of sides in a polygon tends to infinity, that polygon gets closer and closer to a circle. Here is how you can demonstrate this geometric reality by video using Clojure:
(ns video.core
  (:import (java.io File)
           (org.jcodec.api.awt AWTSequenceEncoder)
           (java.awt.image BufferedImage)
           (java.awt Color Polygon Rectangle RenderingHints)))

(defn create-polygon
  [vertices offset rect]

  (let [step (/ (* 2 Math/PI)
                vertices)
        x (int-array vertices)
        y (int-array vertices)
        xradius (/ (.-width rect) 2)
        yradius (/ (.-height rect) 2)]
    (dotimes [i vertices]
      (let [current-x (+ (.-x rect) xradius (int (* (Math/cos (+ offset (* i step))) xradius)))
            current-y (+ (.-y rect) yradius (int (* (Math/sin (+ offset (* i step))) yradius)))]
        (aset x i current-x)
        (aset y i current-y)))
    (Polygon. x y vertices)))

(defn main
  []

  (let [file (File.
               (str
                 (System/getProperty "user.home")
                 "/Media/out.mp4"))
        encoder (AWTSequenceEncoder/createSequenceEncoder file 5)
        img (BufferedImage. 600 600 BufferedImage/TYPE_INT_RGB)
        g (.createGraphics img)]
    (.setRenderingHint g RenderingHints/KEY_ANTIALIASING RenderingHints/VALUE_ANTIALIAS_ON)

    (dotimes [i 80]
      (.setColor g Color/WHITE)
      (.fillRect g 0 0 600 600)

      (.setColor g Color/BLACK)
      (let [polygon (create-polygon (+ i 3) 0 (Rectangle. 2 2 596 596))]
        (doto g
          (.draw polygon)))

      (.encodeImage encoder img))

    (.finish encoder)))
Here is the resulting video, which visually demonstrates this tendency:

No comments:

Post a Comment