Skip to content

Instantly share code, notes, and snippets.

@nariakiiwatani
Created July 3, 2020 13:51
Show Gist options
  • Save nariakiiwatani/de319adf73e2caa05238c748b247c57b to your computer and use it in GitHub Desktop.
Save nariakiiwatani/de319adf73e2caa05238c748b247c57b to your computer and use it in GitHub Desktop.
(defn fix-distance
[base desire distance]
(let [angle (vec2/angle (vec2/- desire base))]
(vec2/rotate base angle (vec2/+ base [distance 0]))))
(defn make-chain
{:params [{:label "src" :type "any"}
{:label "step" :type "number"}
{:overwrap "overwrap" :type "number" :default 0}]
}
[src step overwrap]
(for [base (range 0 (- (count src) (dec step)) (- step overwrap))]
(vec (slice src base (+ base step)))
)
)
(def calc-nodes (fn [root params]
(reduce (fn [a b]
(concat a (let [length (first b)
angle (second b)
lastPos (last a)
newPos (vec2/+ lastPos (vec2/scale [(cos angle) (sin angle)] length))]
[newPos])))
[root] params)))
(defn fabrik-ik
{:handles
{:draw
(fn [{:params [root & params]}]
(reduce (fn [a b]
(concat a (let [index (count a)
length (first b)
angle (second b)
lastPos (get (last a) :pos)
newPos (vec2/+ lastPos (vec2/scale [(cos angle) (sin angle)] length))]
[{:id index
:type "point"
:pos newPos}])))
[{:id 0 :type "point" :pos root}] params)
)
:drag
(fn [{:id id :pos p :params [root & params]}]
(let [solve (fn [root points params]
(reduce (fn [a b]
(let [pindex (dec (count a))
length (first (nth params pindex))
lastPos (last a)
]
(concat a [(fix-distance lastPos b length)])))
[root] points))
pos (replace-nth (calc-nodes root params) id p)
reversed (reverse pos)
stage1 (reverse (solve (first reversed) (rest reversed) (reverse (concat params))))
hoge (prn params)
stage2 (solve root (rest stage1) params)
final stage2
]
(concat [root] (reduce (fn [a b]
(let [index (count a)
from b
to (nth final (inc index))
sub (vec2/- to from)
]
(concat a [[(vec2/len sub) (vec2/angle sub)]])
))
[] (butlast final)))
)
)
}}
[root & params]
(map (fn [[a b]] (line a b)) (make-chain (calc-nodes root params) 2 1))
)
:start-sketch
(style (stroke "salmon" 10)
(fabrik-ik [0 0] [99.9999999999999 (deg 149.73398709666546)] [80.00000000000014 (deg -142.1971986631917)] [60.000000000000114 (deg -167.2019307116476)] [50.00000000000032 (deg 105.45095361200002)] [39.999999999999886 (deg 112.16395891693072)])
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment