aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/interactive-units/bitmap.lisp
blob: cc4b4f7740a315a0d0b80c15eac5d6086ec86b45 (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
;;;; bitmap.lisp

(in-package #:wheelwork)

(defclass/std bitmap (affine interactive)
  ((texture :ri :std (error "A bitmap requires a texture."))
   (vao shader :with :r :static)))

(defmethod initialize-instance :after ((bitmap bitmap) &key)
  (with-slots (vao shader base-width base-height texture) bitmap
    (setf base-height (texture-height texture)
          base-width (texture-width texture))
    (unless shader
      (setf shader
            (create-shader
             '(:vertex
               ((vert :vec2))
               ((transform :mat4))
               ((values
                 (* transform (vari:vec4 vert 0.0 1.0))
                 vert))) ;color
             '(:fragment
               ((tc :vec2))
               ((tex :sampler-2d))
               ((let ((frag  (vari:texture tex tc)))
                  (if (< (aref frag 3) 0.01)
                      (vari:discard)
                      frag))))))
      (gl:program-uniformi
       shader
       (gl:get-uniform-location shader "TEX")
       0))
    (unless vao
      (setf vao (gl:gen-vertex-array))
      (gl:bind-vertex-array vao)
      (let ((vbo (gl:gen-buffer)))
        (with-gl-array (verts :float
                              0.0 1.0 
                              1.0 0.0 
                              0.0 0.0 
                              
                              0.0 1.0 
                              1.0 1.0 
                              1.0 0.0 )
          (gl:bind-buffer :array-buffer vbo)
          (gl:buffer-data :array-buffer :static-draw verts)))
      (gl:enable-vertex-attrib-array 0)
      (gl:vertex-attrib-pointer 0 2 :float 0 (* +float-size+ 2) 0)
      (gl:bind-buffer :array-buffer 0)
      (gl:bind-vertex-array 0))))

(defmethod cleanup ((bitmap bitmap))
  (with-slots (vao shader) bitmap
    (when vao
      (gl:delete-vertex-arrays (list vao)))
    (when shader
      (gl:delete-program shader))
    (setf vao nil
          shader nil)))

(defmethod render ((bitmap bitmap))
  (with-slots (texture vao shader) bitmap
    (gl:active-texture 0)
    (gl:bind-texture :texture-2d (texture-id texture))
    (gl:use-program shader)
    (gl:program-uniform-matrix-4fv
     shader
     (gl:get-uniform-location shader "TRANSFORM")
     (projected-matrix bitmap))
    (gl:bind-vertex-array vao)    
    (gl:draw-arrays :triangles 0 6)
    (gl:bind-vertex-array 0)))