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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
|
;;;; wheelwork.lisp
(in-package #:wheelwork)
(defvar *application* nil
"current application")
(defclass/std unit ()
((cached-model cached-projected-matrix :a)
(container :with :a)
(base-width base-height :r :std 1.0 :doc "Determined by content.")
(scale-x scale-y :with :std 1.0)
(rotation x y :with :std 0.0)
(opacity :std 1.0 :doc "0.0 indicates it will not be rendred.")))
(defgeneric unit-width (unit))
(defgeneric unit-height (unit))
(defgeneric (setf unit-width) (newval unit))
(defgeneric (setf unit-height) (newval unit))
(defun scale-by (unit amount)
(with-slots (scale-x scale-y) unit
(setf scale-x (* amount scale-x)
scale-y (* amount scale-y))))
(defun set-width-preserve-aspect (unit new-width)
(scale-by unit (/ new-width (unit-width unit))))
(defun set-height-preserve-aspect (unit new-height)
(scale-by unit (/ new-height (unit-height unit) )))
(defmethod unit-width ((unit unit))
(with-slots (scale-x base-width) unit
(* scale-x base-width)))
(defmethod unit-height ((unit unit))
(with-slots (scale-y base-height) unit
(* scale-y base-height)))
(defmethod (setf unit-width) (newval (unit unit))
(with-slots (scale-x base-width) unit
(setf scale-x (coerce (/ newval base-width) 'single-float))))
(defmethod (setf unit-height) (newval (unit unit))
(with-slots (scale-y base-height) unit
(setf scale-y (coerce (/ newval base-height) 'single-float))))
(defmethod (setf closer-mop:slot-value-using-class) :after
(newval class (unit unit) slot)
(case (closer-mop:slot-definition-name slot)
((x y scale-x scale-y rotation)
(setf (cached-model unit) nil
(cached-projected-matrix unit) nil))))
(defclass/std container ()
((units :with :a))
(:documentation "Just a list of units. Made into a class so that
transformation affine transformations methods can be specialzied on
whole groups of units"))
(defgeneric drop-unit (unit))
(defgeneric add-unit (container unit))
(defmethod drop-unit ((unit unit))
"Removes a unit from its container. Returns T if the unit actually was removed."
(when-let (container (unit-container unit))
(setf
(container-units container) (delete unit (container-units container))
(unit-container unit) nil)
t))
(defmethod add-unit ((container container) (unit unit))
"Adds a unit to the end of a container (thus affecting render
order). Makes sure to remove the unit from its current container if
necessary."
(when (unit-container unit)
(drop-unit unit))
(setf
(container-units container)
(nconc (container-units container)
(list unit))
(unit-container unit) container)
unit)
(defclass/std event-handler ()
((event-type handler-function :ri))
(:metaclass closer-mop:funcallable-standard-class))
(defmethod initialize-instance :after ((eh event-handler) &key)
(with-slots (handler-function) eh
(closer-mop:set-funcallable-instance-function eh handler-function)))
(defclass/std listener ()
((keydown
keyup
mousedown
mouseup
mousemotion
mousewheel
focus
blur
perframe
after-added
before-added
before-dropped
:r :with :type (or null event-handler) :std nil)
(keydown-table
keyup-table
mousedown-table
mouseup-table
mousemotion-table
mousewheel-table
focus-table
blur-table
perframe-table
after-added-table
before-added-table
before-dropped-table
:static
:std (make-hash-table :synchronized t)
:doc "Keyed by DISPLAY-UNIT instance, holds an EVENT-HANDLER if handler is defined for unit."))
(:documentation "Event handlers per object. The static hash tables
are keyed by UNIT and hold Event-Handler instances."))
(defclass/std interactive ()
((listener :type (or null listener) :std nil :a)
(focusablep :std t :doc "Whether or not this object can receive application focus."))
(:documentation "Supplies an object with a listener slot."))
(defmethod drop-unit :before ((unit interactive))
(when (unit-container unit)
(when-let (handlers (get-handlers-for unit 'before-dropped))
(dolist (handler handlers)
(funcall handler unit)))))
(defmethod add-unit :before ((container container) (unit interactive))
(when-let (handlers (get-handlers-for unit 'before-added))
(dolist (handler handlers)
(funcall handler container unit))))
(defmethod add-unit :after ((container container) (unit interactive))
(when-let (handlers (get-handlers-for unit 'after-added))
(dolist (handler handlers)
(funcall handler container unit))))
(defun listener-table-for (listener event-type)
(ecase event-type
(keydown (keydown-table listener))
(keyup (keyup-table listener))
(mousedown (mousewheel-table listener))
(mouseup (mouseup-table listener))
(mousemotion (mousemotion-table listener))
(mousewheel (mousewheel-table listener))
(focus (focus-table listener))
(blur (blur-table listener))
(perframe (perframe-table listener))
(after-added (after-added-table listener))
(before-added (before-added-table listener))
(after-dropped (after-dropped-table listener))
(before-dropped (before-dropped-table listener))))
(defun add-handler (interactive handler)
(when (null (listener interactive))
(setf (listener interactive) (make-instance 'listener)))
(pushnew handler (slot-value (listener interactive) (event-type handler)) :test #'eq)
(setf
(gethash interactive (listener-table-for (listener interactive) (event-type handler)))
t))
(defun remove-handler (interactive handler-or-event-type)
"Handler can be an instance of EVENT-HANDLER or can be a symbol
whose name is an event type. If is an event handler, only that
handler will be removed. If it is an event type, all events of that
type name are removed from the object."
(when (listener interactive)
(let ((event-type (etypecase handler-or-event-type
(keyword (intern (symbol-name handler-or-event-type) :wheelwork))
(symbol (intern (symbol-name handler-or-event-type) :wheelwork))
(event-handler (event-type handler-or-event-type)))))
(setf (slot-value (listener interactive) event-type)
(if (symbolp handler-or-event-type)
;; remove everything if a symbol
nil
;; delete just the handler
(delete handler-or-event-type
(slot-value (listener interactive) event-type)
:test #'eq)))
;; remove from from the global table unless any listeners remain on this event
(unless (slot-value (listener interactive) event-type)
(remhash interactive (listener-table-for (listener interactive) event-type))))))
(defun should-listen-for-p (event-type &optional (app *application*))
(plusp (hash-table-count (listener-table-for (listener app) event-type))))
(defclass/std application (container interactive)
((title :with :std "Wheelwork App")
(asset-root :ri :std #P"./" :doc "Directory under which assets are stored.")
(asset-classifiers
:std '(("png" png) ("ttf" font))
:doc "ALIST of (EXT CLASS). EXT is a string, file estension. CLASS is a symbol, class name.")
(assets :with :a :std (make-hash-table :test 'equal)
:doc "maps asset names to asset instances.")
(scale :with :std 1.0)
(width height :with :std 800)
(projection :with :a :doc "The projection matrix for the scene. Orthographic by default.")
(window :with :a)
(refocus-on-mousedown-p :std t)
(focus last-motion-target :with :a)
(fps :with :std 30 :doc "Frames Per Second")
(frame-wait :r)))
(defun fps (&optional (app *application*))
(application-fps app))
(defun (setf fps) (new-val &optional (app *application*))
(setf (application-fps app) new-val))
(defun can-set-projection-p (app)
(and (slot-boundp app 'width)
(slot-boundp app 'height)
(slot-boundp app 'scale)))
(defun set-projection (app)
(when (can-set-projection-p app)
(with-slots (projection scale width height) app
;; set projection matrix
(setf projection (mat:mortho 0.0 (/ width scale) 0 (/ height scale) -1.0 1.0)))))
(defmethod initialize-instance :after ((app application) &key)
(set-projection app)
(setf (listener app) (make-instance 'listener)))
(defun fire-blur-event-on (thing)
(when-let (blur-handlers (and thing (get-handlers-for thing 'blur)))
(dolist (handler blur-handlers)
(funcall handler thing))))
(defun fire-focus-event-on (thing)
(when-let (focus-handlers (and thing (get-handlers-for thing 'focus)))
(dolist (handler focus-handlers)
(funcall handler thing))))
(defmethod (setf closer-mop:slot-value-using-class ) :before
(new-value class (app application) slot)
(case (closer-mop:slot-definition-name slot)
(focus
(when (slot-boundp app 'focus)
(unless (eq new-value (slot-value app 'focus))
(fire-blur-event-on (slot-value app 'focus))
(fire-focus-event-on new-value))))))
(defmethod (setf closer-mop:slot-value-using-class) :after
(new-value class (app application) slot)
(case (closer-mop:slot-definition-name slot)
((scale width height)
(set-projection app))
(fps
(setf (slot-value app 'frame-wait) (/ 1.0 new-value)))))
(defgeneric boot (app)
(:documentation "Specialized for each subclass of
APPLICATION. Responsble for setting the app up once the system
resoruces are avaialble.")
(:method ((app application)) nil))
(defgeneric shutdown (app)
(:documentation "Specialzied for each subclass of
APPLICATION. Called just before cleanup.")
(:method ((app application)) nil))
(defgeneric cleanup (thing)
(:documentation "Clean up applications, textures, and so on.")
(:method ((any t)) nil))
(defparameter +listener-table-slot-names+
'(keydown-table keyup-table mousedown-table mouseup-table mousemotion-table
focus-table blur-table perframe-table after-added-table before-added-table
before-dropped-table))
(defmethod cleanup ((app application))
(loop for asset being the hash-value of (application-assets app)
do (cleanup asset))
;; drop all current handlers
(let ((listener (listener app)))
(dolist (table +listener-table-slot-names+)
(setf (slot-value listener table) (make-hash-table :synchronized t))))
(call-next-method))
(defmethod cleanup ((container container))
(dolist (u (container-units container))
(cleanup u)))
(defun start (app &key (x :centered) (y :centered))
(sdl2:with-init (:everything)
(sdl2:gl-set-attr :context-major-version 3)
(sdl2:gl-set-attr :context-minor-version 3)
(sdl2:gl-set-attr :context-profile-mask
sdl2-ffi:+sdl-gl-context-profile-core+)
(sdl2:gl-set-attr :doublebuffer 1)
(sdl2:with-window (window
:flags '(:shown :opengl)
:title (application-title app)
:w (application-width app)
:h (application-height app)
:x x :y y)
(setf (application-window app) window)
(sdl2:with-gl-context (ctx window)
(sdl2:gl-make-current window ctx)
(gl:viewport 0 0 (application-width app) (application-height app))
(gl:enable :depth-test)
(let ((*application* app))
(unwind-protect
(progn
(boot app)
(eventloop app)
(shutdown app))
(cleanup app)))))))
(defgeneric render (thing))
(defmethod render ((app application))
(let ((table (perframe-table (listener app)))
(time (get-universal-time)))
(loop for target being the hash-key of table
for handlers = (slot-value (listener target) 'perframe)
do (loop for handler in handlers do (funcall handler target time))))
(gl:clear-color 0.0 0.0 0.0 1.0)
(gl:clear :depth-buffer-bit :color-buffer-bit)
(dolist (thing (container-units app))
(render thing))
(sdl2:gl-swap-window (application-window app))
(sleep (frame-wait app)))
(defgeneric model-matrix (thing)
(:documentation "Returns the model matrix"))
(defgeneric projected-matrix (thing)
(:documentation "Returns the raw array of the model matrix after it
has been prjected by the application's projecion matrix"))
(defmethod model-matrix :around ((u unit))
(or (cached-model u)
(setf (cached-model u)
(call-next-method))))
(defmethod model-matrix ((u unit))
(let ((m (mat:meye 4)))
(with-slots (x y base-width scale-x base-height scale-y rotation) u
(let ((uw (* base-width scale-x))
(uh (* base-height scale-y)))
(mat:nmtranslate m (vec:vec x y 0.0))
(mat:nmtranslate m (vec:v* 0.5 (vec:vec uw uh 0.0)))
(mat:nmrotate m vec:+vz+ rotation)
(mat:nmtranslate m (vec:v* -0.5 (vec:vec uw uh 0.0)))
(mat:nmscale m (vec:vec uw uh 1.0))))
m))
(defmethod projected-matrix ((thing unit))
(or (cached-projected-matrix thing)
(setf (cached-projected-matrix thing)
(mat:marr (mat:m* (application-projection *application*)
(model-matrix thing))))))
(defgeneric ensure-loaded (asset)
(:documentation "Ensures that the asset is loaded into memory and ready for use. Returns the asset."))
(defclass/std asset ()
((path :with :ri :std (error "An asset requires a path"))
(loadedp :with :a)))
(defmethod cleanup :around ((asset asset))
(when (asset-loadedp asset)
(call-next-method))
(setf (asset-loadedp asset) nil))
(defmethod ensure-loaded :around ((thing asset))
(unless (asset-loadedp thing)
(call-next-method)
(setf (asset-loadedp thing) t))
thing)
(defclass/std texture ()
((width height id mipmap :with :r)
(internal-format image-format :ri :with :std :rgba)
(wrap-s wrap-t :ri :with :std :repeat)
(min-filter mag-filter :ri :with :std :nearest)))
(defmethod cleanup ((texture texture))
(gl:delete-texture (texture-id texture)))
(defclass/std png (asset texture) ())
(defmethod ensure-loaded ((png png))
(with-slots
(width height id wrap-s wrap-t min-filter mag-filter internal-format image-format)
png
(pngload:with-png-in-static-vector (data (asset-path png) :flip-y t)
(setf width (pngload:width data)
height (pngload:height data)
id (gl:gen-texture))
(gl:bind-texture :texture-2d id)
(gl:tex-parameter :texture-2d :texture-wrap-s wrap-s)
(gl:tex-parameter :texture-2d :texture-wrap-t wrap-t)
(gl:tex-parameter :texture-2d :texture-min-filter min-filter)
(gl:tex-parameter :texture-2d :texture-mag-filter mag-filter)
(gl:tex-image-2d :texture-2d
0
internal-format
width
height
0
image-format
:unsigned-byte
(pngload:data data))
(gl:bind-texture :texture-2d 0)
(when (texture-mipmap png)
(gl:generate-mipmap :texture-2d)))))
(defun refocus-on (target &optional (app *application*))
"Sets focus of application to TARGET. This works whether or not
TARGET is FOCUSABLEP"
(setf (application-focus app) target))
(defun get-focus (&optional (app *application*))
(or (application-focus app) app))
(defun get-handlers-for (unit event-type)
"EVENT-TYPE must be one of the slot value names for WHEELWORK::LISTENER."
(?> (unit) listener #$(slot-value $listener event-type)))
(defun eventloop-keydown (app sdl-keysym)
(let ((target (get-focus app)))
(when-let (handlers (get-handlers-for target 'keydown))
(dolist (handler handlers)
(apply handler
target
(sdl2:scancode sdl-keysym)
(sdl2:mod-keywords (sdl2:mod-value sdl-keysym)))))))
(defun eventloop-keyup (app sdl-keysym)
(let ((target (get-focus app)))
(when-let (handlers (get-handlers-for target 'keyup))
(dolist (handler handlers)
(apply handler
target
(sdl2:scancode sdl-keysym)
(sdl2:mod-keywords (sdl2:mod-value sdl-keysym)))))))
(defun get-rect (unit)
(with-accessors ((x unit-x) (y unit-y) (w unit-width) (h unit-height) (r unit-rotation)) unit
(let ((m
(mat:meye 4))
(tr
(vec:vec (+ x (* 0.5 w)) (+ y (* 0.5 h)) 0.0)))
(mat:nmtranslate m tr)
(mat:nmrotate m vec:+vz+ r)
(mat:nmtranslate m (vec:v* -1.0 tr))
(list (mat:m* m (vec:vec x y 0.0 1.0))
(mat:m* m (vec:vec x (+ y h) 0.0 1.0))
(mat:m* m (vec:vec (+ x w) (+ y h) 0.0 1.0))
(mat:m* m (vec:vec (+ x w) y 0.0 1.0))
(mat:m* m (vec:vec x y 0.0 1.0))))))
(defun counterclockwisep (a b c)
(> (* (- (vec:vx b) (vec:vx a))
(- (vec:vy c) (vec:vy a)))
(* (- (vec:vy b) (vec:vy a))
(- (vec:vx c) (vec:vx a)))))
(defun intersectp (a b c d)
(or (vec:v= a c) (vec:v= a d) (vec:v= b c) (vec:v= b d)
(and (not (eq (counterclockwisep a c d) (counterclockwisep b c d)))
(not (eq (counterclockwisep a b c) (counterclockwisep a b d))))))
(defun contains-point-p (unit px py)
(let ((pt
(vec:vec px py 0.0 1.0))
(corner
(vec:vec 0.0 0.0 0.0 1.0))
(poly
(get-rect unit)))
(loop for (p1 p2 . more) on poly
while p2
when (intersectp p1 p2 pt corner)
count 1 into intersection-count
finally
(progn
(return (oddp intersection-count))))))
(defun unit-under (app x y)
(labels
((finder (thing)
(etypecase thing
(container
(find-if #'finder (container-units thing) :from-end t))
(unit
(when (contains-point-p thing x y)
(return-from unit-under thing))))))
(finder app)))
(defun screen-to-world (x y &optional (app *application*))
(with-slots (height scale) app
(list (/ x scale) (/ (- height y) scale))))
(defun eventloop-mousebuttondown (app wx wy clicks button)
"Searches for a handler to handle applies it if found.
Additionally, if the APPLICATION's REFOCUS-ON-MOUSEDOWN-P is T, try to
give focus to whatever was clicked."
(destructuring-bind (x y) (screen-to-world wx wy)
(let ((target
(or (unit-under app x y) ; if no unit is under the mouse,
app))) ; then target the app itself
(when (and (refocus-on-mousedown-p app) (focusablep target))
(refocus-on target))
(when-let (handlers (get-handlers-for target 'mousedown))
(dolist (handler handlers)
(funcall handler target x y clicks button wx wy))))))
(defun eventloop-mousebuttonup (app wx wy clicks button)
(when (should-listen-for-p 'mouseup app)
(destructuring-bind (x y) (screen-to-world wx wy)
(when-let* ((target (or (unit-under app x y)
app))
(handlers (get-handlers-for target 'mouseup)))
(dolist (handler handlers)
(funcall handler target x y clicks button wx wy))))))
(defun eventloop-mousemotion (app wx wy wxrel wyrel state)
(when (should-listen-for-p 'mousemotion app)
(destructuring-bind (x y) (screen-to-world wx wy)
(destructuring-bind (xrel yrel) (screen-to-world wxrel wyrel)
(when-let* ((target (or (unit-under app x y)
app))
(handlers (get-handlers-for target 'mousemotion)))
(dolist (handler handlers)
(funcall handler target x y xrel yrel state wx wy wxrel wyrel)))))))
(defun eventloop-mousewheel (app wx wy dir)
(when (should-listen-for-p 'mousewheel app)
(when-let* ((focus (get-focus app))
(handlers (get-handlers-for focus 'mousewheel)))
(dolist (handler handlers)
(funcall handler focus wx wy dir)))))
(defun eventloop (app)
(sdl2:with-event-loop (:method :poll)
(:mousebuttondown
(:x x :y y :clicks clicks :button button)
(eventloop-mousebuttondown app x y clicks button))
(:mousemotion
(:x x :y y :xrel xrel :yrel yrel :state state)
(eventloop-mousemotion app x y xrel yrel state))
(:mousebuttonup
(:x x :y y :clicks clicks :button button)
(eventloop-mousebuttonup app x y clicks button))
(:keydown
(:keysym keysym)
(eventloop-keydown app keysym))
(:keyup
(:keysym keysym)
(eventloop-keyup app keysym))
(:mousewheel
(:x x :y y :direction dir)
(eventloop-mousewheel app x y dir))
(:idle () (render app))
(:quit () t)))
(defclass/std bitmap (unit interactive)
((texture :ri :std (error "A bitmap requires a texture."))
(vao shader :with :r :static)))
(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)))
(defun shader-by-type (type)
(case type
(:vertex :vertex-shader)
(:geometry :geometry-shader)
(:fragment :fragment-shader)))
(defun gl-shader (type stage)
(let ((shader (gl:create-shader type)))
(gl:shader-source shader (varjo:glsl-code stage))
(gl:compile-shader shader)
(unless (gl:get-shader shader :compile-status)
(error "failed to compile ~a shader:~%~a~%"
type (gl:get-shader-info-log shader)))
shader))
(defun create-shader (&rest sources)
(let* ((stages
(varjo:rolling-translate
(mapcar (lambda (source)
(destructuring-bind (type inputs uniforms code) source
(varjo:make-stage type inputs uniforms '(:330) code)))
sources)))
(shaders
(loop
:for stage :in stages
:for source :in sources
:collect (gl-shader (shader-by-type (car source))
stage)))
(program (gl:create-program)))
(dolist (shader shaders) (gl:attach-shader program shader))
(gl:link-program program)
(unless (gl:get-program program :link-status)
(error "failed to link program: ~%~a~%"
(gl:get-program-info-log program)))
(dolist (shader shaders)
(gl:detach-shader program shader)
(gl:delete-shader shader))
program))
(defun gl-array (type &rest contents)
(let ((array (gl:alloc-gl-array type (length contents))))
(dotimes (i (length contents) array)
(setf (gl:glaref array i) (elt contents i)))))
(defmacro with-gl-array ((var type &rest contents) &body body)
`(let ((,var (gl-array ,type ,@contents)))
(unwind-protect (progn ,@body)
(gl:free-gl-array ,var))))
(define-symbol-macro +float-size+
(cffi:foreign-type-size :float))
(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 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)))
(defun asset-class-for (asset-id &optional (app *application*))
"Given an asset-id (see GET-ASSET), retrieve the symbol name of a
the class that will be used to instantiate the asset object. That
class should be a subclass of ASSET. Additional clases can be added
to the application's ASSET-CLASSIFIERS association list."
(second (assoc (pathname-type asset-id) (asset-classifiers app) :test #'string-equal)))
(defun get-asset (asset-id &key (app *application*) asset-args)
"ASSET-ID is a pathname namestring relative to the application's
ASSET-ROOT. GET-ASSET retrieves an already-available asset from the
application's ASSETS table, or, if not available, loads the asset from
disk.
ASSET-ARGS is a plist to pass to make-instance for the given resource.
"
(or (gethash asset-id (application-assets app))
(setf (gethash asset-id (application-assets app))
(ensure-loaded
(apply 'make-instance
(asset-class-for asset-id)
:path (uiop:merge-pathnames* asset-id (asset-root app))
asset-args)))))
(define-symbol-macro +standard-font-chars+
"
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz01234567890\".,!?-'" )
(defclass/std font (asset)
((characters :i :std +standard-font-chars+)
(oversample :i :doc "ovesampling factor to pass to cl-fond:make-font")
(object :with :r :doc "The font as returned from cl-fond:make-font")))
(defmethod ensure-loaded ((font font))
(with-slots (path characters oversample object) font
(setf object (cl-fond:make-font path characters :oversample oversample))))
(defclass/std text (unit interactive)
((font :with :ri :std (error "A font is required") :type font)
(content :with :ri :std "")
(color :with :std #(1.0 1.0 1.0 1.0))
(vao elem-count newlines :r)
(shader :with :static :r)))
(defmethod model-matrix ((text text))
(let ((m (mat:meye 4)))
(with-slots (font newlines x y base-width base-height scale-x scale-y rotation) text
(let* ((text-height
(cl-fond:text-height (font-object font)))
(baseline-offset
(* newlines text-height))
(rotation-baseline-offset
(* 2 newlines text-height )))
(mat:nmtranslate m (vec:vec x
(+ y
(*
scale-y
baseline-offset))
0.0))
(mat:nmtranslate m (vec:v* 0.5 (vec:vec (* scale-x base-width)
(* scale-y (- base-height rotation-baseline-offset) )
0.0)))
(mat:nmrotate m vec:+vz+ rotation)
(mat:nmtranslate m (vec:v* -0.5 (vec:vec (* scale-x base-width )
(* scale-y (- base-height rotation-baseline-offset))
0.0))))
(mat:nmscale m (vec:vec scale-x scale-y 1.0))
m)))
(defmethod initialize-instance :after ((text text) &key)
(with-slots (content newlines font vao elem-count shader base-width base-height scale-x scale-y) text
(unless shader
(setf shader
(create-shader
'(:vertex
((vert :vec2) (col :vec2))
((transform :mat4))
((values
(* transform (vari:vec4 vert 0.0 1.0))
col)))
'(:fragment
((tc :vec2))
((tex :sampler-2d)
(color :vec4))
((* color (aref (vari:texture tex tc) 0)))))))
(multiple-value-bind (vao% count%) (cl-fond:compute-text (font-object font) content)
(setf vao vao%
elem-count count%))
(setf newlines (count #\newline content))
(hq:with-plist (l r) (cl-fond:compute-extent (font-object font) content)
(setf base-width (- r l)
base-height (* (cl-fond:text-height (font-object font))
(1+ newlines))))))
(defmethod cleanup ((text text))
(with-slots (vao shader) text
(gl:delete-vertex-arrays (list vao))
(when shader
(gl:delete-program shader))
(setf vao nil
shader nil)))
(defmethod render ((text text))
(with-slots (shader font vao elem-count color) text
(gl:use-program shader)
(gl:active-texture 0)
(gl:bind-texture :texture-2d (cl-fond:texture (font-object font)))
(gl:program-uniform-matrix-4fv
shader
(gl:get-uniform-location shader "TRANSFORM")
(projected-matrix text))
(gl:program-uniformi
shader
(gl:get-uniform-location shader "TEX")
0)
(gl:program-uniformfv
shader
(gl:get-uniform-location shader "COLOR")
color)
(gl:bind-vertex-array vao)
(%gl:draw-elements :triangles elem-count :unsigned-int 0)
(gl:bind-vertex-array 0)))
(defmacro defhandler (name handler)
"Defines a handler - binds (FDEFINITION NAME) to HANDLER, which
should be an expression that evaluates to an instance of
EVENT-HANDLER, which is funcallable. It is define such that handlers
can be redefined using this form to support interactive development."
(let ((handler-var (gensym)))
`(let ((,handler-var ,handler))
(if-let (extant (and (fboundp ',name)
(fdefinition ',name)))
(closer-mop:set-funcallable-instance-function extant (handler-function ,handler-var))
(setf (fdefinition ',name) ,handler-var)))))
(defmacro on-perframe
((&optional (target 'target) (time 'time)) &body body)
"Creates a handler for 'PERFRAME events"
`(make-instance
'event-handler
:event-type 'wheelwork::perframe
:handler-function (lambda (,(intern (symbol-name target))
,(intern (symbol-name time)))
(declare (ignorable ,(intern (symbol-name target))
,(time (intern (symbol-name time)))))
,@body)))
(defmacro on-keydown
((&optional (target 'target) (scancode 'scancode) (modifiers 'modifiers)) &body body)
"Creates a lambda suitable for the value of a keydown event
handler. The function accepts two positional arguments TARGET and
SCANCODE and one &REST argument MODIFIERS.
SCANCODE will be a keyword of the form :SCANCODE-A, :SCANCODE-B ...
The members of MODIFIERS look like :LSHIFT, :RCTRL, RALT, etc"
`(make-instance
'event-handler
:event-type 'wheelwork::keydown
:handler-function (lambda (,(intern (symbol-name target))
,(intern (symbol-name scancode))
&rest ,(intern (symbol-name modifiers)))
(declare (ignorable ,(intern (symbol-name target))
,(intern (symbol-name scancode))
,(intern (symbol-name modifiers))))
,@body)))
(defmacro on-keyup
((&optional (target 'target) (scancode 'scancode) (modifiers 'modifiers)) &body body)
"Creates a lambda suitable for the value of a keyup event
handler. The function accepts two positional arguments TARGET and
SCANCODE and one &REST argument MODIFIERS.
SCANCODE will be a keyword of the form :SCANCODE-A, :SCANCODE-B ...
The members of MODIFIERS look like :LSHIFT, :RCTRL, RALT, etc"
`(make-instance
'event-handler
:event-type 'wheelwork::keyup
:handler-function (lambda (,(intern (symbol-name target))
,(intern (symbol-name scancode))
&rest ,(intern (symbol-name modifiers)))
(declare (ignorable ,(intern (symbol-name target))
,(intern (symbol-name scancode))
,(intern (symbol-name modifiers))))
,@body)))
(defmacro on-mousemotion
((&optional
(target 'target)
(x 'x) (y 'y)
(xrel 'xrel) (yrel 'yrel)
(state 'state)
(win-x 'win-x) (win-y 'win-y)
(win-xrel 'win-xrel) (win-yrel 'win-yrel))
&body body)
"Creates a handler for MOUSEMOTION events"
`(make-instance
'event-handler
:event-type 'wheelwork::mousemotion
:handler-function (lambda (,(intern (symbol-name target))
,(intern (symbol-name x))
,(intern (symbol-name y))
,(intern (symbol-name xrel))
,(intern (symbol-name yrel))
,(intern (symbol-name state))
,(intern (symbol-name win-x))
,(intern (symbol-name win-y))
,(intern (symbol-name win-xrel))
,(intern (symbol-name win-yrel)))
(declare (ignorable ,(intern (symbol-name target))
,(intern (symbol-name x))
,(intern (symbol-name y))
,(intern (symbol-name xrel))
,(intern (symbol-name yrel))
,(intern (symbol-name state))
,(intern (symbol-name win-x))
,(intern (symbol-name win-y))
,(intern (symbol-name win-xrel))
,(intern (symbol-name win-yrel))))
,@body)))
(defmacro on-mousedown
((&optional (target 'target)
(x 'x) (y 'y)
(clicks 'clicks) (button 'button)
(win-x 'win-x) (win-y 'win-y))
&body body)
"Creates a handler for MOUSEDOWN events"
`(make-instance
'event-handler
:event-type 'wheelwork::mousedown
:handler-function (lambda
(,(intern (symbol-name target))
,(intern (symbol-name x))
,(intern (symbol-name y))
,(intern (symbol-name clicks))
,(intern (symbol-name button))
,(intern (symbol-name win-x))
,(intern (symbol-name win-y)))
(declare
(ignorable ,(intern (symbol-name target))
,(intern (symbol-name x))
,(intern (symbol-name y))
,(intern (symbol-name clicks))
,(intern (symbol-name button))
,(intern (symbol-name win-x))
,(intern (symbol-name win-y))))
,@body)))
(defmacro on-mouseup
((&optional (target 'target)
(x 'x) (y 'y)
(clicks 'clicks) (button 'button)
(win-x 'win-x) (win-y 'win-y))
&body body)
"Creates a handler for MOUSEUP events"
`(make-instance
'event-handler
:event-type 'wheelwork::mouseup
:handler-function (lambda
(,(intern (symbol-name target))
,(intern (symbol-name x))
,(intern (symbol-name y))
,(intern (symbol-name clicks))
,(intern (symbol-name button))
,(intern (symbol-name win-x))
,(intern (symbol-name win-y)))
(declare
(ignorable ,(intern (symbol-name target))
,(intern (symbol-name x))
,(intern (symbol-name y))
,(intern (symbol-name clicks))
,(intern (symbol-name button))
,(intern (symbol-name win-x))
,(intern (symbol-name win-y))))
,@body)))
(defmacro on-mousewheel
((&optional (target 'target) (horiz 'horiz) (vert 'vert) (dir 'dir)) &body body)
"Creates a handler for MOUSEWHEEL events"
`(make-instance
'event-handler
:event-type 'wheelwork::mousewheel
:handler-function (lambda
(,(intern (symbol-name target))
,(intern (symbol-name horiz))
,(intern (symbol-name vert))
,(intern (symbol-name dir)))
(declare
(ignorable ,(intern (symbol-name target))
,(intern (symbol-name horiz))
,(intern (symbol-name vert))
,(intern (symbol-name dir))))
,@body)))
(defmacro on-blur
((&optional (target 'target)) &body body)
"Creates a handler for BLUR events. BLUR is a psuedo event that
fires whenever an object loses focus."
`(make-instance
'event-handler
:event-type 'wheelwork::blur
:handler-function (lambda
(,(intern (symbol-name target)))
(declare
(ignorable ,(intern (symbol-name target))))
,@body)))
(defmacro on-focus
((&optional (target 'target)) &body body)
"Creates a handler for a FOCUS event. FOCUS is a pusedo event that
fires when the FOCUS slot of the current APPLICATION instance is changed.
"
`(make-instance
'event-handler
:event-type 'wheelwork::focus
:handler-function (lambda
(,(intern (symbol-name target)))
(declare
(ignorable ,(intern (symbol-name target))))
,@body)))
(defmacro on-before-dropped
((&optional (target 'target)) &body body)
"Creates a handler for BEFORE-DROPPED events, which fire before a
unit is removed from its container."
`(make-instance
'event-handler
:event-type 'wheelwork::before-dropped
:handler-function (lambda
(,(intern (symbol-name target)))
(declare
(ignorable ,(intern (symbol-name target))))
,@body)))
(defmacro on-before-added
((&optional (container 'container) (target 'target)) &body body)
"Creates a handler for BEFORE-ADDED events, which fire before a unit
is added to a container."
`(make-instance
'event-handler
:event-type 'wheelwork::before-added
:handler-function (lambda
(,(intern (symbol-name container))
,(intern (symbol-name target)))
(declare
(ignorable
,(intern (symbol-name container))
,(intern (symbol-name target))))
,@body)))
(defmacro on-after-added
((&optional (container 'container) (target 'target)) &body body)
"Creates a handler for AFTER-ADDED events, which fire after a unit
is added to a container."
`(make-instance
'event-handler
:event-type 'wheelwork::after-added
:handler-function (lambda
(,(intern (symbol-name container))
,(intern (symbol-name target)))
(declare
(ignorable
,(intern (symbol-name container))
,(intern (symbol-name target))))
,@body)))
;;; Utility
(define-symbol-macro +pi-over-180+ 0.017453292519943295d0)
(defun radians (degrees)
"Converse DEGREES to radians"
(* degrees +pi-over-180+))
|