Advertisement
Yurry

Icosahedron → Sphere

Nov 28th, 2012
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. data Vector = Vector {x, y, z :: Float}
  2.     deriving Show
  3.  
  4. len (Vector x y z) = sqrt $ (x ^ 2) + (y ^ 2) + (z ^ 2)
  5.  
  6. (Vector ax ay az) +. (Vector bx by bz) = Vector (ax + bx) (ay + by) (az + bz)
  7. (Vector ax ay az) -. (Vector bx by bz) = Vector (ax - bx) (ay - by) (az - bz)
  8. k *. (Vector ax ay az) = Vector (k * ax) (k * ay) (k * az)
  9. normalize vec = (recip $ len vec) *. vec
  10. (Vector ax ay az) `scal` (Vector bx by bz) = ax * bx + ay * by + az * bz
  11.  
  12. type Face = (Vector, Vector, Vector)
  13. type Figure = [Face]
  14.  
  15. icosahedron radius = top ++ middleTop ++ middleBottom ++ bottom
  16.     where north = Vector 0 0 radius
  17.           south = Vector 0 0 (-radius)
  18.           topv = [Vector (radius * cos a) (radius * sin a) z | a <- init [0, 2 * pi / 5 .. 2 * pi]]
  19.           botv = [Vector (radius * cos a) (radius * sin a) (-z) | a <- init [pi / 5, 3 * pi / 5 .. 2 * pi + pi / 5]]
  20.           z = radius * (1 + sqrt 5) / 2
  21.           top = [(north, a, b) | (a, b) <- zip topv (cycle topv)]
  22.           bottom = [(south, a, b) | (a, b) <- zip botv (cycle botv)]
  23.           middleTop = zip3 topv (cycle topv) botv
  24.           middleBottom = zip3 botv (cycle botv) (cycle topv)
  25.           cycle list = last list : init list
  26.  
  27. cut :: Float -> Face -> [Face]
  28. cut r f@(fa, fb, fc) = [(fa, fab, fac), (fb, fbc, fac), (fc, fac, fbc)]
  29.     where fab = hr *. normalize (fa +. fb)
  30.           fbc = hr *. normalize (fb +. fc)
  31.           fac = hr *. normalize (fa +. fc)
  32.           hr = r / 2
  33.  
  34. triangulate :: Int -> Figure -> Figure
  35. triangulate iter src = iterate subdivide src !! iter
  36.     where subdivide = concatMap cutR :: Figure -> Figure
  37.           cutR = cut (len . fst3 . head $ src) :: Face -> [Face]
  38.           fst3 (a, _, _) = a
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement