summaryrefslogtreecommitdiff
path: root/examples/model.scm
blob: cc7391821c3dd5521ad66a55ec9ae1cdc02ebb6a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
(use-modules (chickadee)
             (chickadee math)
             (chickadee math matrix)
             (chickadee math vector)
             (chickadee render)
             (chickadee render model)
             (chickadee render font)
             (ice-9 format))

(define projection (perspective-projection (/ pi 3) (/ 4.0 3.0) 0.1 500.0))
(define rotation (make-identity-matrix4))
(define translation (make-identity-matrix4))
(define view-matrix (make-identity-matrix4))
(define model-matrix (make-identity-matrix4))
(define position (vec3 0.0 0.0 0.0))
(define velocity (vec3 0.0 0.0 0.0))
(define model #f)
(define text-position #v(4.0 464.0))
(define text "")
(define y-rotation 0.0)

(define (reset-position)
  (set-vec3! position 0.0 0.0 -4.0))

(define (load)
  (set! model (load-obj "models/suzanne.obj"))
  (reset-position))

(define (draw alpha)
  (with-projection projection
    (with-depth-test #t
      (draw-model model model-matrix view-matrix)))
  (draw-text text text-position))

(define (update dt)
  ;; Update camera position
  (set-vec3! velocity
             (+ (if (key-pressed? 'd) -1.0 0.0)
                (if (key-pressed? 'a) 1.0 0.0))
             0.0
             (+ (if (key-pressed? 's) -1.0 0.0)
                (if (key-pressed? 'w) 1.0 0.0)))
  (vec3-normalize! velocity)
  (vec3-mult! velocity 0.1)
  (vec3-add! position velocity)
  (set! text (format #f "(~6,2f, ~6,2f, ~6,2f)"
                     (vec3-x position)
                     (vec3-y position)
                     (vec3-z position)))

  ;; Compute new view matrix
  (matrix4-rotate-y! rotation theta)
  (matrix4-translate! translation position)
  (matrix4-identity! view-matrix)
  (matrix4-mult! view-matrix view-matrix rotation)
  (matrix4-mult! view-matrix view-matrix translation)

  ;; Rotate the model about the y-axis
  (set! y-rotation (+ y-rotation 0.03))
  (matrix4-rotate-y! model-matrix y-rotation))

(define (key-press key scancode modifiers repeat?)
  (cond
   ((eq? key 'q)
    (abort-game))
   ((eq? key 'r)
    (reset-position))))

(run-game #:window-title "3D!"
          #:load load
          #:draw draw
          #:update update
          #:key-press key-press)