forked from Mon-Ouie/blocky
-
Notifications
You must be signed in to change notification settings - Fork 0
/
console.lisp
2596 lines (2159 loc) · 83.9 KB
/
console.lisp
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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
;;; console.lisp --- OS/device driver for BLOCKY
;; Copyright (C) 2006-2013 David O'Toole
;; Author: David O'Toole <dto@ioforms.org>
;; Keywords: multimedia, games
;; This file 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, or (at your option)
;; any later version.
;; This file 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; see the file COPYING. If not, write to
;; the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
;; Boston, MA 02110-1301, USA.
;;; Commentary:
;; The "console" is the library which provides all BLOCKY system
;; services. Primitive operations such as opening a window, rendering
;; text, displaying bitmaps, drawing lines, playing sounds, file
;; access, and device input are all handled here.
;; Currently it uses the cross-platform SDL library (via
;; LISPBUILDER-SDL) as its device driver, and wraps the library for
;; use by the rest of BLOCKY.
;; http://lispbuilder.sourceforge.net/
;; The OpenGL support here is derived from code written by Bart Botta
;; for his excellent cl-opengl tutorials:
;; http://3bb.cc/tutorials/cl-opengl/
(in-package :blocky)
(defsetf point set-point)
(defvar *minibuffer* nil)
(defvar *minibuffer-open-p* nil)
(defvar *gl-window-open-p* nil)
(defvar *pending-resources* '())
(defun add-resource (plist)
(assert (and (consp plist)
(keywordp (first plist))))
(push plist *pending-resources*))
(defun add-resources (plists)
(mapcar #'add-resource plists))
(defun random-choose (set)
(nth (random (length set)) set))
(defmacro restartably (&body body)
`(restart-case
(progn ,@body)
(continue () :report "Continue" )))
;;; Keyboard state
;; (see also keys.lisp for the symbol listing)
(defun keyboard-id (key)
"Look up the SDL symbol corresponding to the BLOCKY symbol KEY. See keys.lisp."
(let* ((entry (find key *key-identifiers* :key #'first))
(entry2 (find (second entry) *sdl-key-identifiers* :key #'second)))
(first entry2)))
(defun keyboard-mod (mod)
"Look up the SDL symbol corresponding to the BLOCKY symbol MOD. See keys.lisp."
(let* ((entry (find mod *key-modifiers* :key #'first))
(entry2 (find (second entry) *sdl-key-modifiers* :key #'second)))
(first entry2)))
(defun keyboard-held-p (key)
"Returns the duration in seconds that the key has been depressed over a number of game loops."
(sdl:key-held-p (keyboard-id key)))
(defun keyboard-pressed-p (key)
"Returns t if the key has just been depressed in the current game loop."
(sdl:key-pressed-p (keyboard-id key)))
(defun keyboard-released-p (key)
"Returns t if the key has just been released in the current game loop."
(sdl:key-released-p (keyboard-id key)))
(defun keyboard-time-in-current-state (key)
"Returns the duration in seconds that key is either pressed or depressed."
(sdl:key-time-in-current-state (keyboard-id key)))
(defun keyboard-time-in-previous-state (key)
"Returns the duration in seconds that key was in its previous state either pressed or depressed."
(sdl:key-time-in-previous-state (keyboard-id key)))
(defun keyboard-down-p (key)
"Returns t if the key is depressed."
(sdl:key-down-p (keyboard-id key)))
(defun keyboard-modifier-down-p (mod)
"Returns t if the modifier key is depressed."
(sdl:mod-down-p (keyboard-mod mod)))
(defun keyboard-keys-down ()
"Returns a list of the keys that are depressed."
(labels ((translate (key)
(let ((entry (find key *sdl-key-identifiers* :key #'first)))
(let ((entry2 (find (second entry) *key-identifiers* :key #'second)))
(first entry2)))))
(mapcar #'translate (sdl:keys-down-p))))
(defun keyboard-modifiers ()
"Returns a list of the modifier keys that are depressed."
(labels ((translate (mod)
(let ((entry (find mod *sdl-key-modifiers* :key #'first)))
(let ((entry2 (find (second entry) *key-modifiers* :key #'second)))
(first entry2)))))
(mapcar #'translate (sdl:mods-down-p))))
(defun holding-control ()
(or (keyboard-modifier-down-p :lctrl)
(keyboard-modifier-down-p :rctrl)))
(defun holding-alt ()
(or (keyboard-modifier-down-p :lalt)
(keyboard-modifier-down-p :ralt)))
(defun holding-shift ()
(or (keyboard-modifier-down-p :lshift)
(keyboard-modifier-down-p :rshift)))
;;; Logging messages to the standard output
(defparameter *message-logging* t)
(defun message-to-standard-output (message-string)
(format t "~A" message-string)
(fresh-line)
(force-output))
(defparameter *message-function* #'message-to-standard-output)
(defun reset-message-function ()
(setf *message-function* #'message-to-standard-output))
(defvar *message-hook* nil)
(defvar *message-history* nil)
(defun message (format-string &rest args)
"Print a log message by passing the arguments to
`*message-function'. When the variable `*message-logging*' is nil,
this output is disabled."
(let ((message-string (apply #'format nil format-string args)))
(when *message-logging*
(funcall *message-function* message-string))
(dolist (hook *message-hook*)
(funcall hook))
(push message-string *message-history*)))
;;; Sequence numbers
(defvar *sequence-number* 0)
(defun genseq (&optional (x 0))
"Generate an all-purpose sequence number."
(+ x (incf *sequence-number*)))
;;; Hooks
(defun add-to-list (list element)
(assert (and (symbolp list)
(not (null list))))
(setf (symbol-value list)
(append (symbol-value list)
(list element))))
(defun add-hook (hook func)
"Hooks are special variables whose names are of the form
`*foo-hook*' and whose values are lists of functions taking no
arguments. The functions of a given hook are all invoked (in list
order) whenever the hook is run with `run-hook'.
This function arranges for FUNC to be invoked whenever HOOK is triggered with
`run-hook'. The function should have no arguments."
(pushnew func (symbol-value hook)))
(defun remove-hook (hook func)
"Stop calling FUNC whenever HOOK is triggered."
(setf (symbol-value hook)
(delete func (symbol-value hook))))
(defun run-hook (hook)
"Call all the functions in HOOK, in list order."
(dolist (func (symbol-value hook))
(funcall func)))
;;; The active blocks list
;; see also blocks.lisp
(defvar *blocks* nil "List of active block objects.
These blocks receive input events and are rendered to the screen by
the console. See also `send-event'.
Do not set this variable directly from a project; instead, call
`install-blocks'.")
(defun hit-blocks (x y &optional (blocks *blocks*))
(when blocks
(let ((x0 (truncate x))
(y0 (truncate y)))
(labels ((try (b)
(send :hit b x0 y0)))
(let ((parent (find-if #'try blocks :from-end t)))
(when parent
(try parent)))))))
(defun draw-blocks ()
"Draw the active blocks to the screen."
(dolist (block *blocks*)
(send :draw block)))
(defun install-blocks (&rest blocks)
"User-level function for setting the active block set. Note that
BLOCKY may override the current block set at any time for system menus
and the like."
(setf *blocks* blocks))
;;; "Classic" key repeat
(defvar *key-repeat-p* nil)
(defvar *key-repeat-delay* 9)
(defvar *key-repeat-interval* 1.2)
(defun key-repeat-p () *key-repeat-p*)
(defun enable-key-repeat (&optional (delay *key-repeat-delay*)
(interval *key-repeat-interval*))
(let ((delay-milliseconds (truncate (* delay (/ 1000.0 *frame-rate*))))
(interval-milliseconds (truncate (* interval (/ 1000.0 *frame-rate*)))))
(sdl:enable-key-repeat delay-milliseconds interval-milliseconds)
(setf *key-repeat-delay* delay)
(setf *key-repeat-interval* interval)
(setf *key-repeat-p* t)))
(defun disable-key-repeat ()
(sdl:disable-key-repeat)
(setf *key-repeat-p* nil))
;;; Parceling out events to blocks
(defvar *pointer-x* 0)
(defvar *pointer-y* 0)
(defvar *event-hook* nil)
(defun send-to-blocks (event &optional (blocks *blocks*))
(dolist (hook *event-hook*)
(funcall hook event))
(labels ((try (block)
(send :handle-event block event)))
(some #'try blocks)))
(defvar *event-handler-function* #'send-to-blocks
"Function to be called with input events. Keyboard, mouse,
and joystick events are represented as 'event lists' of the form:
(STRING . MODIFIERS)
where STRING is a string representing the key or button, and MODIFIERS
is a list of key modifier symbols like :shift, :control, :alt, and so
on.
The modifier list is sorted; thus, events can be compared for
equality with `equal' and used as hashtable keys.")
(defun send-event (event)
(if (null *event-handler-function*)
(error "No event handler function installed.
Please set the variable blocky:*event-handler-function*")
(funcall *event-handler-function* event)))
(defun raw-joystick-event-p (event)
(eq :raw-joystick (first event)))
(defun joystick-event-p (event)
(or (raw-joystick-event-p event)
(eq :joystick (first event))))
(defun normalize-event (event)
"Convert EVENT to a normal form suitable for `equal' comparisons."
;; don't sort joystick event modifiers
(if (joystick-event-p event)
event
(cons (first event)
(sort (remove-duplicates (delete nil (rest event)))
#'string< :key #'symbol-name))))
;;; Input events for keyboard and joystick etc
(defvar *joystick-button-symbols*
'(:a :b :x :y ;; face buttons
:left :right :up :down ;; directional pad
:select :start ;; menu buttons
:left-trigger :left-bumper :right-trigger :right-bumper ;; shoulder buttons
:left-click :right-click)) ;; clicking the analog sticks
(defparameter *other-modifier-symbols* '(:button-down :button-up))
(defun make-key-modifier-symbol (sdl-mod)
"Translate from the SDL key modifier symbol SDL-MOD to our own
key event symbols."
(if (or (member sdl-mod *joystick-button-symbols*)
(member sdl-mod *other-modifier-symbols*))
sdl-mod
(case sdl-mod
(:SDL-KEY-MOD-NONE nil)
(:SDL-KEY-MOD-LSHIFT :shift)
(:SDL-KEY-MOD-RSHIFT :shift)
(:SDL-KEY-MOD-LCTRL :control)
(:SDL-KEY-MOD-RCTRL :control)
(:SDL-KEY-MOD-LALT :alt)
(:SDL-KEY-MOD-RALT :alt)
(:SDL-KEY-MOD-LMETA :meta)
(:SDL-KEY-MOD-RMETA :meta)
;; for compatibility:
(:SDL-KEY-NONE nil)
(:SDL-KEY-LSHIFT :shift)
(:SDL-KEY-RSHIFT :shift)
(:SDL-KEY-LCTRL :control)
(:SDL-KEY-RCTRL :control)
(:SDL-KEY-LALT :alt)
(:SDL-KEY-RALT :alt)
(:SDL-KEY-LMETA :meta)
(:SDL-KEY-RMETA :meta)
;; fix for windows
(:SDL-KEY-MOD-NUM nil)
(:SDL-KEY-CAPS :caps-lock)
(:SDL-KEY-MOD-CAPS :caps-lock) ;; macintosh
(:SDL-KEY-MODE nil)
(:SDL-KEY-MOD-MODE :mode)
(:SDL-KEY-RESERVED nil)
)))
(defun make-key-symbol (sdl-key)
"Translate from :SDL-KEY-X to the symbol :X ."
(let ((prefix "SDL-KEY-")
(name (symbol-name sdl-key)))
(assert (search prefix name))
(make-keyword (subseq name (length prefix)))))
(defun make-event (code modifiers)
"Create an input event for the key CODE with MODIFIERS pressed.
The argument CODE may be one of:
- a keyword symbol naming the keyboard key, such as :RETURN or :SPACE
(see also `make-key-symbol'.)
- a one-character string, whose first character is the translated
Unicode character being bound
- an integer whose value is the unicode character code from SDL
or,
- a cons of the form (key unicode) will be passed through
unaltered."
(assert code)
;; pass through joystick events unaltered
(if (joystick-event-p (cons code modifiers))
(cons code modifiers)
(let ((head
(etypecase code
(integer (string (code-char code)))
(string (prog1 code
(assert (= 1 (length code)))))
(keyword code)
(cons code))))
(normalize-event
(cons head
;; modifiers
(cond ((keywordp modifiers)
(list modifiers))
((listp modifiers)
modifiers)
;; catch apparent lispbuilder-sdl bug?
((eql 0 modifiers)
nil)))))))
(defparameter *default-joystick-profile*
'(:name "Unknown Joystick"
:type :joystick
:left-analog-stick (0 1)
:right-analog-stick (3 2)
:buttons ()))
(defvar *joystick-profile* *default-joystick-profile*)
(defvar *user-joystick-profile* nil)
(defvar *joystick-device* nil
"The SDL device id of the current joystick.")
(defparameter *joystick-profiles* nil)
;; '(("DragonRise Inc. Generic USB Joystick "
;; :name "Generic USB Gamepad" :type :joystick
;; :left-analog-stick (0 1)
;; :right-analog-stick (3 2)
;; :buttons ((2 . :a)
;; (1 . :b)
;; (3 . :x)
;; (0 . :y)
;; (6 . :left-bumper)
;; (7 . :right-bumper)
;; (8 . :select)
;; (9 . :start)
;; (4 . :left-trigger)
;; (5 . :right-trigger)))
;; ("GreenAsia Inc. USB Joystick "
;; :name "Generic USB Gamepad" :type :joystick
;; :left-analog-stick (0 1)
;; :right-analog-stick (3 2)
;; :buttons ((2 . :a)
;; (1 . :b)
;; (3 . :x)
;; (0 . :y)
;; (4 . :left-bumper)
;; (5 . :right-bumper)
;; (8 . :select)
;; (9 . :start)
;; (6 . :left-trigger)
;; (7 . :right-trigger)))
;; ("USB Dance Pa"
;; :name "Generic USB Dance Pad" :type :dance
;; :buttons ((12 . :up)
;; (15 . :left)
;; (13 . :right)
;; (14 . :down)
;; (0 . :downleft)
;; (3 . :downright)
;; (2 . :upleft)
;; (1 . :upright)
;; (8 . :select)
;; (9 . :start)))
;; ("GASIA CORP. PS(R) Gamepad Adaptor"
;; :name "Generic USB Gamepad" :type :joystick
;; :left-analog-stick (0 1)
;; :right-analog-stick (2 3)
;; :buttons ((4 . :up)
;; (7 . :left)
;; (5 . :right)
;; (6 . :down)
;; (12 . :downleft)
;; (16 . :downright)
;; (14 . :upleft)
;; (13 . :upright)
;; (14 . :b)
;; (13 . :a)
;; (15 . :y)
;; (12 . :x)
;; (0 . :select)
;; (3 . :start)))))
(defun find-joystick-profile-by-name (name)
(let ((entry (assoc name *joystick-profiles* :test 'equal)))
(when entry (cdr entry))))
(defun find-joystick-profile (indicator)
(etypecase indicator
(string (find-joystick-profile-by-name indicator))
(list indicator)))
(defun joystick-profile ()
(or *user-joystick-profile* *joystick-profile*))
(defun joystick-name (&optional (profile (joystick-profile)))
(getf (find-joystick-profile profile) :name))
(defun joystick-type (&optional (profile (joystick-profile)))
(getf (find-joystick-profile profile) :type))
(defun joystick-buttons (&optional (profile (joystick-profile)))
(getf (find-joystick-profile profile) :buttons))
(defun joystick-left-analog-stick (&optional (profile (joystick-profile)))
(getf (find-joystick-profile profile) :left-analog-stick))
(defun joystick-right-analog-stick (&optional (profile (joystick-profile)))
(getf (find-joystick-profile profile) :right-analog-stick))
(defun button-to-symbol (button)
(cdr (assoc button (joystick-buttons))))
(defun symbol-to-button (sym)
(let ((entry (some #'(lambda (x)
(when (eq sym (cdr x))
x))
(joystick-buttons))))
(when entry
(car entry))))
;; Analog sticks
(defparameter *joystick-axis-size* 32768.0)
(defparameter *joystick-dead-zone* 6000)
(defvar *joystick-axis-values* (make-array 100 :initial-element 0))
(defun update-joystick-axis (axis value)
(setf (aref *joystick-axis-values* axis) value))
(defun joystick-axis-raw-value (axis)
(aref *joystick-axis-values* axis))
(defun joystick-axis-pressed-p (axis)
(< *joystick-dead-zone* (abs (joystick-axis-raw-value axis))))
(defun joystick-axis-value (axis)
(/ (joystick-axis-raw-value axis)
*joystick-axis-size*))
(defun find-heading (x0 y0 x1 y1)
(atan (- y1 y0)
(- x1 x0)))
(defun opposite-heading (heading)
(- pi heading))
(defun analog-stick-pressed-p (&optional (stick (joystick-left-analog-stick)))
(destructuring-bind (horizontal vertical) stick
(or (joystick-axis-pressed-p horizontal)
(joystick-axis-pressed-p vertical))))
(defun left-analog-stick-pressed-p ()
(analog-stick-pressed-p (joystick-left-analog-stick)))
(defun right-analog-stick-pressed-p ()
(analog-stick-pressed-p (joystick-right-analog-stick)))
(defun analog-stick-heading (&optional (stick (joystick-left-analog-stick)))
(destructuring-bind (horizontal vertical) stick
(when (analog-stick-pressed-p stick)
(find-heading 0 0
(joystick-axis-raw-value horizontal)
(joystick-axis-raw-value vertical)))))
(defun analog-stick-pressure (&optional (stick (joystick-left-analog-stick)))
(destructuring-bind (horizontal vertical) stick
(if (or (joystick-axis-pressed-p horizontal)
(joystick-axis-pressed-p vertical))
(/ (distance 0 0
(joystick-axis-value horizontal)
(joystick-axis-value vertical))
;; scale to [0.0, 1.0]
(sqrt 2))
0.0)))
(defun left-analog-stick-heading ()
(analog-stick-heading (joystick-left-analog-stick)))
(defun right-analog-stick-heading ()
(analog-stick-heading (joystick-right-analog-stick)))
(defun left-analog-stick-pressure ()
(analog-stick-pressure (joystick-left-analog-stick)))
(defun right-analog-stick-pressure ()
(analog-stick-pressure (joystick-right-analog-stick)))
;; Joystick buttons
(defvar *joystick-button-states* nil)
(defun poll-joystick-button (button)
"Return 1 if the button numbered BUTTON is pressed, otherwise 0."
(sdl-cffi::sdl-joystick-get-button *joystick-device* button))
(defun update-joystick-button (button state)
"Update the table in `*joystick-button-states*' to reflect the STATE of
the BUTTON. STATE should be either 1 (on) or 0 (off)."
(setf (aref *joystick-button-states* button) state))
(defun joystick-button-state (button)
(poll-joystick-button button))
;; (aref *joystick-button-states* button))
(defun joystick-button-pressed-p (button)
(let ((button-number (if (integerp button)
button
(symbol-to-button button))))
(when button-number
(= 1 (joystick-button-state button-number)))))
(defun reset-joysticks ()
"Re-open the joystick device and re-initialize the state."
(setf *joystick-device* (sdl-cffi::sdl-joystick-open 0))
(setf *joystick-button-states* (make-array 100 :initial-element nil)))
(defun scan-for-joysticks ()
(message "Scanning for connected joysticks...")
(block scanning
(dotimes (index (sdl:num-joysticks))
(let ((joystick (sdl:sdl-joystick-name index)))
(message "Checking joystick ~S, device name: ~S" index joystick)
(let ((profile (find-joystick-profile joystick)))
(if (null profile)
(message "Could not find joystick profile for ~S. Continuing with default profile..." joystick)
(destructuring-bind (&key name type &allow-other-keys) profile
(setf *joystick-profile* profile)
(message "Found joystick profile ~S for ~S." type name))))))))
;;; Frame rate and simulation timing
(defparameter *default-frame-rate* 30)
(defvar *frame-rate* *default-frame-rate*)
(defun set-frame-rate (&optional (rate *frame-rate*))
"Set the frame rate for the game."
(message "Setting frame rate to ~S" rate)
(setf (sdl:frame-rate) rate))
(defun get-ticks ()
(sdl:sdl-get-ticks))
(defvar *dt* 33)
(defvar *next-update-hook* nil)
(defmacro at-next-update (&body body)
`(prog1 nil
(add-hook '*next-update-hook*
#'(lambda () ,@body))))
(defun update-blocks ()
(run-hook '*next-update-hook*)
(setf *next-update-hook* nil)
(dolist (block *blocks*)
(send :update block)))
(defvar *update-function* #'update-blocks)
(defun do-update (&rest args)
(handler-case
(when (functionp *update-function*)
(incf *updates*)
(apply *update-function* args))
(floating-point-inexact (fpe)
(error fpe))))
(defparameter *updates* 0)
;;; Screen dimensions
(defparameter *screen-width* 640 "Physical width of the window, in pixels.")
(defparameter *screen-height* 480 "Physical height of the window, in pixels.")
;; The nominal size of of the window in pixels, in case we just want
;; to scale the scene to match the window instead of showing more of
;; the buffer. If these are the same as the `*screen-' settings
;; above, then more of the buffer will be shown when the window size
;; increases.
(defparameter *nominal-screen-width* 640 "Nominal width of the window, in pixels.")
(defparameter *nominal-screen-height* 480 "Nominal height of the window, in pixels.")
(defparameter *gl-screen-width* 640 "Width of the window expressed in OpenGL coordinates.")
(defparameter *gl-screen-height* 480 "Height of the window expressed in OpenGL coordinates.")
(defparameter *scale-output-to-window* nil
"When non-nil, always show a fixed amount of the buffer when changing
window size. Otherwise (the default) one onscreen pixel equals one
unit of buffer space, so that more of the buffer shows if the window
becomes larger.")
(defparameter *z-near* 0)
(defparameter *z-far* 100)
(defvar *use-texture-blending* t)
(defun enable-texture-blending ()
; (when *use-texture-blending*
(gl:enable :texture-2d :blend))
(defun open-viewport ()
(gl:matrix-mode :projection)
(gl:load-identity)
(gl:viewport 0 0 *screen-width* *screen-height*)
(if *scale-output-to-window*
(setf *gl-screen-width* *nominal-screen-width*
*gl-screen-height* *nominal-screen-height*)
(setf *gl-screen-width* *screen-width*
*gl-screen-height* *screen-height*)))
(defun project-orthographically ()
(gl:disable :depth-test)
(gl:clear :color-buffer-bit)
(enable-texture-blending)
(set-blending-mode :alpha)
(gl:matrix-mode :projection)
(gl:load-identity)
(gl:ortho 0 *gl-screen-width* *gl-screen-height* 0 *z-near* *z-far*))
(defparameter *field-of-view* 45)
(defun project-with-perspective (&key (field-of-view *field-of-view*) (depth *z-far*))
(gl:enable :depth-test)
(gl:clear-depth 1.0)
(gl:clear :color-buffer-bit)
(enable-texture-blending)
(set-blending-mode :alpha)
(gl:matrix-mode :projection)
(gl:load-identity)
;; (glu:perspective field-of-view (/ *gl-screen-width* *gl-screen-height*) *z-near* depth)
(gl:hint :perspective-correction-hint :nicest))
(defvar *window-x* 0)
(defvar *window-y* 0)
(defvar *window-z* 0)
(defun window-pointer-x (&optional (x *pointer-x*))
(+ x *window-x*))
(defun window-pointer-y (&optional (y *pointer-y*))
(+ y *window-y*))
(defun transform-window (&key (x 0) (y 0) (z 0) (scale-x 1.0) (scale-y 1.0) (scale-z 1.0))
(setf *window-x* x)
(setf *window-y* y)
(setf *window-z* z)
;; now move viewing volume
(gl:matrix-mode :modelview)
(gl:load-identity)
(gl:translate (- 0 x)
(- 0 y)
(- 0 z))
(gl:scale scale-x scale-y scale-z))
(defvar *resizable* t)
(defparameter *resize-hook* nil)
;;; The main loop of BLOCKY
(defvar *after-startup-hook* nil)
(defvar *quitting* nil)
(defvar *fullscreen* nil "When non-nil, attempt to use fullscreen mode.")
(defvar *window-title* "blocky")
(defvar *window-position* :center
"Controls the position of the game window. Either a list of coordinates or the symbol :center.")
(defun start-session ()
"Initialize the console, open a window, and play.
We want to process all inputs, update the game state, then update the
display."
(let ((fps (make-instance 'sdl:fps-mixed
:dt (setf *dt* (truncate (/ 1000 *frame-rate*))))))
(message "Simulation update time set to ~d milliseconds." *dt*)
(message "Creating OpenGL window...")
(cond (*fullscreen*
(sdl:window *screen-width* *screen-height*
:fps fps
:title-caption *window-title*
:flags (logior sdl:SDL-FULLSCREEN sdl:SDL-OPENGL)
:position *window-position*))
(*resizable*
(sdl:window *screen-width* *screen-height*
:fps fps
:title-caption *window-title*
:flags (logior sdl:SDL-RESIZABLE sdl:SDL-OPENGL)
:position *window-position*))
(t (sdl:window *screen-width* *screen-height*
:fps fps
:flags sdl:SDL-OPENGL
:title-caption *window-title*
:position *window-position*)))
;; cl-opengl needs platform specific support to be able to load GL
;; extensions, so we need to tell it how to do so in lispbuilder-sdl
(setf cl-opengl-bindings:*gl-get-proc-address* #'sdl-cffi::sdl-gl-get-proc-address)
;; get rid of any bogus textures
(when *textures* (delete-all-textures))
;; move along
(message "Creating OpenGL window... Done.")
(setf *gl-window-open-p* t)
(message "SDL driver name: ~A" (sdl:video-driver-name))
(set-frame-rate *frame-rate*)
(reset-joysticks)
(scan-for-joysticks)
(open-viewport)
(project-orthographically)
(load-project-lisp "STANDARD") ;; TODO remove
(run-hook '*after-startup-hook*)
(message "Finished initializing Blocky for project ~A." *project*)
(sdl:with-events ()
(:quit-event () (prog1 t (sdl:quit-sdl :force t)))
(:video-resize-event (:w w :h h)
(setf *screen-width* w
*screen-height* h)
; (run-hook '*resize-hook*)
(sdl:resize-window w h :title-caption *window-title*
:flags (logior sdl:SDL-OPENGL sdl:SDL-RESIZABLE))
(open-viewport)
(project-orthographically)
;; handle any blitzed textures. on some platforms/drivers
;; the textures become invalidated after resize
(when *clear-cached-images-on-resize*
(clear-cached-images)
(clear-cached-text-images))
)
(:mouse-motion-event (:x x :y y)
(setf *pointer-x* x *pointer-y* y)
(let ((block (hit-blocks (window-pointer-x)
(window-pointer-y)
*blocks*)))
(when block
(send :handle-point-motion block
(window-pointer-x)
(window-pointer-y)))))
(:mouse-button-down-event (:button button :x x :y y)
(setf *pointer-x* x *pointer-y* y)
(let ((block (hit-blocks
(window-pointer-x)
(window-pointer-y)
*blocks*)))
(when block
(send :press block
(window-pointer-x)
(window-pointer-y)
button))))
(:mouse-button-up-event (:button button :x x :y y)
(setf *pointer-x* x *pointer-y* y)
(let ((block (hit-blocks
(window-pointer-x)
(window-pointer-y)
*blocks*)))
(when block
(send :release block
(window-pointer-x)
(window-pointer-y)
button))))
(:joy-button-down-event (:button button :state state)
(send-event (make-event :raw-joystick (list button :button-down)))
(when (assoc button (joystick-buttons))
(update-joystick-button button state)
(send-event (make-event :joystick
(list (button-to-symbol button)
:button-down)))))
(:joy-button-up-event (:button button :state state)
(send-event (make-event :raw-joystick (list button :button-up)))
(when (assoc button (joystick-buttons))
(update-joystick-button button state)
(send-event (make-event :joystick
(list (button-to-symbol button)
:button-up)))))
(:joy-axis-motion-event (:axis axis :value value)
(update-joystick-axis axis value))
(:video-expose-event () (sdl:update-display))
(:key-down-event (:key key :mod-key mod :unicode unicode)
(send-event
(make-event
;; translate data items from SDL format to internal
(cons (make-key-symbol key)
(when (not (zerop unicode))
(string (code-char unicode))))
(mapcar #'make-key-modifier-symbol mod))))
; (:key-up-event (:key key :mod-key mod :unicode unicode)
(:idle ()
;; this lets slime keep working while the main loop is running
;; in sbcl using the :fd-handler swank:*communication-style*
#+(and sbcl (not sb-thread)) (restartably
(sb-sys:serve-all-events 0))
(sdl:with-timestep (do-update))
;; load pending resources
;; (dolist (plist *pending-resources*)
;; (index-resource (apply #'make-resource plist)))
;; (setf *pending-resources* nil)
(restartably
(gl:clear-color 0 0 0 1)
(gl:clear)
(draw-blocks)
(gl:flush)
(sdl:update-display))))))
;;; The user configuration file
(defparameter *user-init-file-name* "blocky-init.lisp")
(defun load-user-init-file ()
(let ((type :unspecific)) ;; possible sbcl non-compliant behavior
(let ((file (merge-pathnames (make-pathname :name *user-init-file-name*
:type type)
(blocky-directory))))
(when (cl-fad:file-exists-p file)
(load (cl-fad:pathname-as-file file))))))
(defparameter *user-keyboard-layout* :qwerty)
(defparameter *use-sound* t "Non-nil (the default) is to use sound. Nil disables sound.")
;;; BLX resource interchange files
(defparameter *resource-file-extension* ".blx"
"BLX is a simple Lisp data interchange file format. An BLX file can
contain one or more data resources. A 'resource' is an image, sound,
text, font, lisp program, or other data whose interpretation is up to
the client.
An BLX resource can be either self-contained, or point to an
external file for its data.
A 'resource record' defines a resource. A resource record is a
structure with the following elements:
:NAME A string; the name of the resource.
The colon character : is reserved and used to specify
resource transformations; see below.
:TYPE A keyword symbol identifying the data type.
Corresponding handlers are the responsibility of the client.
See also `*resource-handlers*' and `load-resource'.
The special type :blx is used to load the blx file
specified in :FILE, from (optionally) another project
whose name is given in :DATA.
The special type :alias is used to provide multiple names
for a resource. The :DATA field contains the name of the
target resource. This name can specify resource
transformations, see below.
:PROPERTIES Property list with extra data; for example :copyright,
:license, :author.
The special property :AUTOLOAD, when non-nil causes
the resource to be loaded automatically upon startup
(the default is to load resources on demand.)
:FILE Name of file to load data from, if any.
Relative to directory of BLX file.
:DATA Lisp data encoding the resource itself, if any.
In memory, these will be represented by resource structs (see below).
On disk, it's Lisp data printed as text. This text should compress very
well.
The string '()' is a valid .BLX file; it contains no resources.")
(defstruct resource
name type properties file data object system-p)
;; The extra `object' field is not saved in .BLX files; it is used to
;; store driver-dependent loaded resources (i.e. SDL image surface
;; objects and so on). This is used in the resource table.
;; The system-p field is likewise not stored.
(defun resource-to-plist (res)
"Convert the resource record RES into a property list.
This prepares it for printing as part of a BLX file."
(list :name (resource-name res)
:type (resource-type res)
:properties (resource-properties res)
:file (resource-file res)
:data (resource-data res)
:object nil))
;; First we need routines to read and write raw s-expressions to and
;; from text files.
(defvar *keyword-package* (find-package :keyword))
(defun write-sexp-to-file (filename sexp)
(message "Writing data to file ~S" filename)
(with-open-file (file filename :direction :output
:if-exists :supersede
:if-does-not-exist :create)
(let ((*package* *keyword-package*))
(with-standard-io-syntax
(print sexp file))))
;;(format file "~S" sexp)))
(message "Writing data to file ~S... Done." filename))
(defvar *eof-value* (gensym))
(defun read-sexp-from-file (filename)
(message "Reading data from ~A..." filename)
(with-open-file (file filename :direction :input)
(with-standard-io-syntax
(let ((*read-eval* nil))