blob: 3bcda5258a8e0fd4229b30a119669fad1d839458 (
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
|
;;; Chickadee Game Toolkit
;;; Copyright © 2016 David Thompson <davet@gnu.org>
;;;
;;; Chickadee is free software: you can redistribute it and/or modify
;;; it under the terms of the GNU General Public License as published
;;; by the Free Software Foundation, either version 3 of the License,
;;; or (at your option) any later version.
;;;
;;; Chickadee is distributed in the hope that it will be useful, but
;;; WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;;; General Public License for more details.
;;;
;;; You should have received a copy of the GNU General Public License
;;; along with this program. If not, see
;;; <http://www.gnu.org/licenses/>.
(define-module (chickadee math)
#:export (square
clamp
min
max)
#:replace (min max))
(define-inlinable (square x)
(* x x))
(define-inlinable (clamp min max x)
"Restrict X to the range defined by MIN and MAX. Assumes that MIN is
actually less than MAX."
(cond ((< x min) min)
((> x max) max)
(else x)))
;; Some macro trickery to inline calls to min/max with 2 arguments.
;; We often call min/max on floating point values, so inlining such
;; calls allows the compiler to unbox many of these operations,
;; reducing allocation.
(define-syntax min
(syntax-rules ()
((_ a b)
(if (< a b) a b))
((_ a b ...)
(let ((m (min b ...)))
(if (< a m) a m)))))
(define-syntax max
(syntax-rules ()
((_ a b) (if (> a b) a b))
((_ a b ...)
(let ((m (max b ...)))
(if (> a m) a m)))))
|