Skip to content

Instantly share code, notes, and snippets.

@thobbs
Created July 8, 2016 01:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thobbs/2ff51b5cfdd67c57972d077669ce912a to your computer and use it in GitHub Desktop.
Save thobbs/2ff51b5cfdd67c57972d077669ce912a to your computer and use it in GitHub Desktop.
Code for partial reflections
(let [; pick random points for a "line of reflection"
reflection-start-x (random (w 0.0) (w 0.5))
reflection-start-y (random (h 0.5) (h 1.0))
reflection-end-x (random (w 0.5) (w 1.0))
reflection-end-y (random (h 0.0) (h 0.5))
x-spread (- reflection-end-x reflection-start-x)
y-spread (- reflection-end-y reflection-start-y)
max-spread (max x-spread y-spread)
; Pre-calculate incremental steps along the line of reflection (as offsets from the start of the line)
; To increase fidelity, change 1.0 to a lower value to avoid skipping pixels (but much slower)
x-steps (for [i (range 0 max-spread 1.0)]
(- (interpolate reflection-start-x reflection-end-x (/ (float i) max-spread))
reflection-start-x))
y-steps (for [i (range 0 max-spread 1.0)]
(- (interpolate reflection-start-y reflection-end-y (/ (float i) max-spread))
reflection-start-y))
pix (pixels)
row-len (int (w))
max-index (dec (* (w) (h)))]
; iterate along a "reference point" on the line of reflection, and then scan in columns
; that are perpendicular to the line of reflection, starting at the reference point
(doseq [[reference-x reference-y] (zip (for [step x-steps] (+ reflection-start-x step))
(for [step y-steps] (+ reflection-start-y step)))]
(doseq [[x-step y-step] (zip x-steps y-steps)]
(let [flip? false
src-x (- reference-x y-step)
src-y (+ reference-y x-step)
dest-x (+ reference-x y-step)
dest-y (- reference-y x-step)
[src-x src-y dest-x dest-y] (if flip?
[dest-x dest-y src-x src-y]
[src-x src-y dest-x dest-y])]
(when (and (between? src-x 0 (w))
(between? src-y 0 (h))
(between? dest-x 0 (w))
(between? dest-y 0 (h)))
(let [src-index (+ (* row-len (int src-y)) (int src-x))
dest-index (+ (* row-len (int dest-y)) (int dest-x))]
; make sure src and dest pixels are in bounds
(when (and (between? src-index 0 max-index)
(between? dest-index 0 max-index))
; copy the pixel
(let [src-pixel (get pix src-index)
dest-pixel (get pix dest-index)]
(aset-int pix dest-index src-pixel)))))))))
(update-pixels))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment