74839fef0a211c3123b56709ae5ecd3976b1cf43
[guile-sdl2.git] / sdl2.scm
1 ;;; guile-sdl2 --- FFI bindings for SDL2
2 ;;; Copyright © 2015 David Thompson <davet@gnu.org>
3 ;;;
4 ;;; This file is part of guile-sdl2.
5 ;;;
6 ;;; Guile-sdl2 is free software; you can redistribute it and/or modify
7 ;;; it under the terms of the GNU Lesser General Public License as
8 ;;; published by the Free Software Foundation; either version 3 of the
9 ;;; License, or (at your option) any later version.
10 ;;;
11 ;;; Guile-sdl2 is distributed in the hope that it will be useful, but
12 ;;; WITHOUT ANY WARRANTY; without even the implied warranty of
13 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 ;;; General Public License for more details.
15 ;;;
16 ;;; You should have received a copy of the GNU Lesser General Public
17 ;;; License along with guile-sdl2. If not, see
18 ;;; <http://www.gnu.org/licenses/>.
19
20 ;;; Commentary:
21 ;;
22 ;; SDL initialization and error handling.
23 ;;
24 ;;; Code:
25
26 (define-module (sdl2)
27 #:use-module (ice-9 match)
28 #:use-module (srfi srfi-4)
29 #:use-module (system foreign)
30 #:use-module ((sdl2 bindings) #:prefix ffi:)
31 #:export (sdl-error-string
32 sdl-error
33 sdl-version
34 sdl-init
35 sdl-quit
36 sdl-ticks))
37
38 (define %default-init-flags
39 '(timer audio video haptic game-controller events))
40
41 (define (sdl-error-string)
42 "Return the current SDL error string."
43 (pointer->string (ffi:sdl-get-error)))
44
45 (define (sdl-error func message . args)
46 (apply throw 'sdl-error func (string-append message ": ~A")
47 (append args (list (sdl-error-string)))))
48
49 (define (sdl-version)
50 "Return a three element list containing the major, minor, and patch
51 version of the linked SDL library."
52 (let ((bv (make-u8vector 3)))
53 (ffi:sdl-get-version (bytevector->pointer bv))
54 (u8vector->list bv)))
55
56 (define* (sdl-init #:optional (subsystems %default-init-flags))
57 "Initialize the SDL library. This must be called before using any
58 other SDL procedure.
59
60 SUBSYSTEMS is an optional list of symbols that specifies the
61 subsystems to initialize. All subsystems are initialized by default.
62 The possible flags are 'timer', 'audio', 'video', 'haptic',
63 'game-controller', and 'events'."
64 (let ((flags (apply logior
65 (map (match-lambda
66 ('timer ffi:SDL_INIT_TIMER)
67 ('audio ffi:SDL_INIT_AUDIO)
68 ('video ffi:SDL_INIT_VIDEO)
69 ('haptic ffi:SDL_INIT_HAPTIC)
70 ('game-controller ffi:SDL_INIT_GAMECONTROLLER)
71 ('events ffi:SDL_INIT_EVENTS))
72 subsystems))))
73 (unless (zero? (ffi:sdl-init flags))
74 (sdl-error "sdl-init" "failed to initialize subsystems ~S"
75 subsystems))))
76
77 (define (sdl-quit)
78 "Quit all activated SDL subsystems. This procedure should be called
79 upon all exit conditions."
80 (ffi:sdl-quit))
81
82 (define (sdl-ticks)
83 "Return the number of milliseconds since the SDL library
84 initialization."
85 (ffi:sdl-get-ticks))