Source

doodle / doodle.scm

Full commit
  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
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
;; Doodle - Drawing and gaming made easy
;;
;; Copyright (c) 2012, Christian Kellermann
;; All rights reserved.

;; Redistribution and use in source and binary forms, with or without
;; modification, are permitted provided that the following conditions
;; are met:

;;     Redistributions of source code must retain the above copyright
;;     notice, this list of conditions and the following disclaimer.
;;
;;     Redistributions in binary form must reproduce the above
;;     copyright notice, this list of conditions and the following
;;     disclaimer in the documentation and/or other materials provided
;;     with the distribution.
;;
;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
;; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
;; FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
;; COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
;; INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
;; (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
;; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
;; HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
;; STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
;; ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
;; OF THE POSSIBILITY OF SUCH DAMAGE.

(module doodle
        (*sprites*
         add-sprite!
         check-for-collisions
         circle
         clear-screen
         current-background
         doodle-width
         doodle-height
         draw-line
         filled-circle
         filled-rectangle
         font-color
         font-size
         make-sprite
         new-doodle
         rectangle
         remove-sprite!
         run-event-loop
         save-screenshot
         set-font!
         show!
         solid-black
         solid-white
         text
         update-sprite!
         world-changes
         world-inits
         world-ends)

(import chicken scheme)
(use (srfi 1 4 18) cairo data-structures extras sdl clojurian-syntax)

(define font-color (make-parameter (list 0 0 0 1)))
(define font-size (make-parameter 12))

(define current-background (make-parameter (list 0 0 0 1)))
(define solid-black (list 0 0 0 1))
(define solid-white (list 1 1 1 1))

(define *c* #f)
(define *c-surface* #f)
(define *s* #f)

(define doodle-width #f)
(define doodle-height #f)

(define (expect-procedure p)
  (unless (procedure? p)
    (error "This parameter can be set to procedures only, you gave it " p))
  p)

(define world-ends (make-parameter void expect-procedure))
(define world-changes (make-parameter void expect-procedure))
(define world-inits (make-parameter void expect-procedure))

(define-syntax set-color
  (syntax-rules ()
    ((_ color) (apply cairo-set-source-rgba `(,*c* ,@color)))))

(define (set-font! font size color)
  (font-color color)
  (font-size size)
  (cairo-select-font-face *c* font CAIRO_FONT_SLANT_NORMAL CAIRO_FONT_WEIGHT_NORMAL)
  (cairo-set-font-size *c* (font-size)))

(define (text-width text)
  (define ex (make-cairo-text-extents-type))
  (cairo-set-font-size *c* (font-size))
  (cairo-text-extents *c* text ex)
  (values (cairo-text-extents-width ex)
          (cairo-text-extents-height ex)))

(define (circle x y diameter color)
  (set-color color)
  (doto *c*
        (cairo-arc x y (/ diameter 2) 0 (* 2 cairo-pi))
        (cairo-stroke)))

(define (filled-circle x y diameter color)
  (set-color color)
  (doto *c*
        (cairo-arc x y (/ diameter 2) 0 (* 2 cairo-pi))
        (cairo-fill)))

(define (filled-rectangle x1 y1 width height color)
  (set-color color)
  (doto *c*
        (cairo-new-path)
        (cairo-set-dash (make-f64vector 0) 0 0)
        (cairo-rectangle x1 y1 width height)
        (cairo-fill)
        (cairo-close-path)))

(define (rectangle x1 y1 width height color)
  (set-color color)
  (doto *c*
        (cairo-new-path)
        (cairo-set-dash (make-f64vector 0) 0 0)
        (cairo-rectangle x1 y1 width height)
        (cairo-stroke)
        (cairo-close-path)))

(define (draw-line x1 y1 x2 y2
                   #!key
                   (width 1)
                   (color solid-white)
                   (style #:solid))
  (doto *c*
        (cairo-set-line-width width)
        (cairo-new-path)
        (cairo-move-to x1 y1))
  (set-color color)
  (case style
    ((#:solid)
     (cairo-set-dash *c* (make-f64vector 0) 0 0))
    ((#:dashed)
     (cairo-set-dash *c* (make-f64vector 1 5) 1 0))
    (else (error "unknown line style " style)))
  (doto *c*
        (cairo-line-to x2 y2)
        (cairo-stroke)))

(define (text x y text #!key (align #:left))
  (define (overall-height text)
    (let ((l (if (list? text) text (list text))))
      (fold (lambda (t s)
              (let-values (((w h) (text-width t)))
                          (+ s (* 1.5 h))))
            0
            l)))

  (define (draw-text x y text align)
    (let-values (((w h) (text-width text)))
                (let ((fx (case align
                            ((#:center) (- x (/ w 2)))
                            ((#:left) x)
                            ((#:right (- x w)))
                            (else x)))
                      (fy y))
                  (apply cairo-set-source-rgba `(,*c* ,@(font-color)))
                  (doto *c*
                        (cairo-move-to fx fy)
                        (cairo-set-font-size (font-size))
                        (cairo-show-text text))
                  h)))
  (if (list? text)
      (for-each (let ((y (if (eq? align #:center)
                             (- y (/ (overall-height text) 4))
                             y)))
                  (lambda (t)
                    (set! y (+ y (* 1.5 (draw-text x y t align))))))
                text)
      (draw-text x y text align)))

(define (save-screenshot filename)
  (cairo-surface-write-to-png *c-surface* filename))

(define (insert-image-as-background filename)
  (let* ((width (cairo-image-surface-get-width *c-surface*))
         (height (cairo-image-surface-get-height *c-surface*))
         (img (cairo-image-surface-create-from-png filename))
         (img-width (cairo-image-surface-get-width img))
         (img-height (cairo-image-surface-get-height img)))
    (doto *c*
          (cairo-set-source-rgba 0 0 0 1)
          (cairo-rectangle 0 0 width height)
          (cairo-fill)
          (cairo-stroke)
          (cairo-scale (/ width img-width) (/ height img-height))
          (cairo-set-source-surface img 0 0))
    (cairo-surface-destroy img)))

(define (new-doodle #!key
                    (width 680)
                    (height 460)
                    (title "Doodle")
                    (background solid-black)
                    (fullscreen #f))

  (sdl-init SDL_INIT_EVERYTHING)

  (set! *s* (sdl-set-video-mode width height 32 (+ SDL_HWSURFACE
                                                  SDL_HWPALETTE
                                                  SDL_DOUBLEBUF
                                                  (if fullscreen
                                                      SDL_FULLSCREEN
                                                      0))))
  (set! *c-surface* (cairo-image-surface-create-for-data
              (sdl-surface-pixels *s*)
              CAIRO_FORMAT_RGB24 width height
              (sdl-surface-pitch *s*)))

  (set! *c* (cairo-create *c-surface*))

  (set! doodle-width width)
  (set! doodle-height height)

  (sdl-wm-set-caption title "Pretty Pics Inc.")

  (current-background background)

  (if (string? background)
      (insert-image-as-background background)
      (apply cairo-set-source-rgba `(,*c* ,@background)))

  (doto *c*
        (cairo-rectangle 0 0 width height)
        (cairo-fill)
        (cairo-stroke)
        (cairo-paint))

  (sdl-flip *s*))

(define (clear-screen #!optional (color (current-background)))
(let ((width (cairo-image-surface-get-width *c-surface*))
      (height (cairo-image-surface-get-height *c-surface*)))
  (if (list? color)
      (apply cairo-set-source-rgba `(,*c* ,@color))
      (insert-image-as-background color))
  (doto *c*
        (cairo-rectangle 0 0 width height)
        (cairo-fill)
        (cairo-stroke))))

(define (show!)
  (cairo-surface-flush *c-surface*)
  (sdl-flip *s*))


;; Collision detection

;; sprites are very crude rectangles atm consisting of a name, x, y,
;; width and height in pixels
(define-record sprite name x y width height)
(define *sprites* '())

(define-record-printer (sprite s p)
  (fprintf p "#,(sprite ~s ~s ~s ~s ~s)"
           (sprite-name s)
           (sprite-x s)
           (sprite-y s)
           (sprite-width s)
           (sprite-height s)))

(define (collides? s ss)
  (define (inside? x y s)
     (and (< (sprite-x s) x (+ (sprite-x s) (sprite-width s)))
          (< (sprite-y s) y (+ (sprite-y s) (sprite-height s)))))

  (define (sprite->points s)
    `((,(sprite-x s) ,(sprite-y s))
      (,(+ (sprite-x s) (sprite-width s)) ,(sprite-y s))
      (,(sprite-x s) ,(+ (sprite-height s) (sprite-y s)))
      (,(+ (sprite-x s) (sprite-width s)) ,(+ (sprite-y s) (sprite-height s)))))

  (define (overlap s1 s2)
    (or (any (lambda (xy)
               (inside? (first xy) (second xy) s1))
             (sprite->points s2))
        (any (lambda (xy)
               (inside? (first xy) (second xy) s2))
             (sprite->points s1))))

  (let ((cs (map (cut sprite-name <>)
                  (filter (lambda (s2)
                            (overlap s s2))
                          ss))))
    (and (not (null? cs)) cs)))

(define (check-for-collisions)
  (let loop ((s (map cdr *sprites*))
             (cols '()))
    (cond ((null? s) cols)
          ((collides? (car s) (remove (cut equal? (car s) <>) (map cdr  *sprites*)))
           => (lambda (o) (loop (cdr s) (cons (list (sprite-name (car s)) o) cols))))
          (else (loop (cdr s) cols)))))

(define (remove-sprite! s-name)
  (alist-delete! s-name *sprites* equal?))

(define (update-sprite! s)
  (set! *sprites* (alist-update! (sprite-name s) s *sprites*)))

(define add-sprite! update-sprite!)

;; Event stuff

(define (translate-mouse-event type event)
(let ((x (sdl-event-x event))
      (y (sdl-event-y event)))
  (if (equal? type SDL_MOUSEMOTION)
      (list 'mouse 'moved x y)
      (let ((b (sdl-event-button event)))
        (list 'mouse
              (if (equal? type SDL_MOUSEBUTTONDOWN)
                  'pressed 'released)
              x y b)))))

(define (translate-key-event type event)
  (let ((k (sdl-event-sym event)))
    (list 'key
     (if (equal? type SDL_KEYUP)
         'released 'pressed)
     (cond ((equal? k SDLK_UP)
            'up)
           ((equal? k SDLK_DOWN)
            'down)
           ((equal? k SDLK_LEFT)
            'left)
           ((equal? k SDLK_RIGHT)
            'right)
           ((integer->char k)
            => identity)
           (else 'unknown)))))

(define (translate-events event escape)
  (if (not event)
      #f
      (let ((t (sdl-event-type event)))
        (cond ((equal? t SDL_QUIT)
               (escape 'quit))
              ((equal? t SDL_VIDEOEXPOSE)
               '(redraw))
              ((or (equal? t SDL_MOUSEBUTTONUP)
                   (equal? t SDL_MOUSEBUTTONDOWN)
                   (equal? t SDL_MOUSEMOTION))
               (translate-mouse-event t event))
              ((or (equal? t SDL_KEYDOWN)
                   (equal? t SDL_KEYUP))
               (translate-key-event t event))
              (else (list 'unknown event))))))

(define (collect-events)
  (let pump ((events '()))
    (let ((event (make-sdl-event)))
      (if (sdl-poll-event! event)
          (pump (cons event events))
          (reverse events)))))

(define (event-handler #!optional minimum-wait)
  (lambda ()
    (let ((last (current-milliseconds)))
      (call-with-current-continuation
       (lambda (escape)
         (let loop ()
           (let* ((now (current-milliseconds))
                  (dt (min (/ 1 30) (/ (- now last)
                                       1000))))
             ((world-changes)
              (map (cut translate-events <> escape)
                   (collect-events))
              dt
              escape)
             (show!)
             (set! last now)
             (when (< dt minimum-wait)
               (thread-sleep! (- minimum-wait dt)))
             (loop)))))
      ((world-ends))
      (sdl-quit))))

(define (run-event-loop #!key
                        (run-in-background #f)
                        (minimum-wait 0))
  ((world-inits))
  (sdl-flip *s*)
  (if run-in-background
      (thread-start!
       (make-thread (event-handler minimum-wait) "doodle-event-loop"))
      (thread-join!
       (thread-start!
        (make-thread (event-handler minimum-wait) "doodle-event-loop"))))))