16  2d and 3d geometry with fastmath.vector - DRAFT 🛠

authors: Nedeljko Radovanovic, Epidiah Ravachol, Daniel Slutsky

16.1 Setup

(ns noj-book.fastmath-vector-geom2d3d
  (:require [fastmath.vector :as vec]
            [clojure.math :as math]
            [emmy.mafs :as mafs]
            [scicloj.kindly.v4.kind :as kind]))

16.2 a few operations

16.2.1 rounding

(-> (vec/vec2 1/3 2/3)
    (vec/approx 5))
[0.33333 0.66667]

16.2.2 addition

(vec/add (vec/vec2 -2 -1)
         (vec/vec2 1 4))
[-1.0 3.0]

16.2.3 rotation

Pi radians = 180 degress

(-> (vec/vec2 1 0)
    (vec/rotate math/PI))
[-1.0 1.224646799076922E-16]
(-> (vec/vec2 1 0)
    (vec/rotate math/PI)
    (vec/approx 5))
[-1.0 0.0]

rotating by Pi ratians (90 degrees) around the z axis:

(-> (vec/vec3 1 0 1)
    (vec/rotate 0 0 (/ math/PI 2))
    (vec/approx 5))
[0.0 1.0 1.0]

16.3 visualizing 2d addition

(the parallelogram rule)

(mafs/mafs
 {:viewBox {:x [-5 5 ]
            :y [-5 5]}}
 (mafs/cartesian)
 (mafs/vector [-2 -1] {:color :blue})
 (mafs/vector [1 4] {:color :blue})
 (mafs/vector (vec
               (vec/add (vec/vec2 -2 -1)
                        (vec/vec2 1 4)))
              {:color :red}))

16.4 visualizing 2d rotation

(mafs/mafs
 {:viewBox {:x [-5 5 ]
            :y [-5 5]}}
 (mafs/cartesian)
 (mafs/vector (vec (vec/vec2 -2 -1))
              {:color :blue})
 (mafs/vector (vec (vec/rotate
                    (vec/vec2 -2 -1)
                    (/ math/PI 2)))
              {:color :red}))

16.5 visualizing 3d rotation

(defn vec3d->plotly-coords [v]
  {:x [0 (v 0)]
   :y [0 (v 1)]
   :z [0 (v 2)]
   :type :scatter3d
   :mode :lines+markers
   :line {:width 10}
   :marker {:size 4}})
(let [orig-v (vec/vec3 1 0 0)]
  (kind/plotly
   {:data [(vec3d->plotly-coords orig-v)
           (vec3d->plotly-coords (vec/rotate orig-v
                                             0
                                             (/ math/PI 10)
                                             0))]}))
(def random-shape
  (repeatedly 6
              (fn []
                (vec/vec3 (+ 1 (rand))
                          (+ 2 (rand))
                          0))))
(defn shape->plotly-coords [shape]
  {:x (mapv #(% 0) shape)
   :y (mapv #(% 1) shape)
   :z (mapv #(% 2) shape)
   :type :scatter3d
   :mode :markers+lines
   :line {:width 10}
   :marker {:size 4}})
(kind/plotly
 {:data [(shape->plotly-coords random-shape)
         (shape->plotly-coords
          (map #(vec/rotate %
                            0
                            0
                            Math/PI)
               random-shape))
         (shape->plotly-coords [[0 0 0]])]})
random-shape
([1.553612017548991 2.9846859656720848 0.0]
 [1.6738099091982304 2.7640360231154206 0.0]
 [1.954425344123703 2.3638397182447335 0.0]
 [1.7662174253240075 2.684724947731341 0.0]
 [1.9140097757210999 2.590825833572514 0.0]
 [1.693692063896856 2.2543033208012457 0.0])
source: notebooks/noj_book/fastmath_vector_geom2d3d.clj