Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/resttime/cl-liballegro

Common Lisp bindings and interface to the Allegro 5 game programming library
https://github.com/resttime/cl-liballegro

allegro5 bindings cffi common-lisp game-dev game-development gamedev lisp

Last synced: 2 months ago
JSON representation

Common Lisp bindings and interface to the Allegro 5 game programming library

Awesome Lists containing this project

README

        

#+TITLE: cl-liballegro
#+OPTIONS: ^:nil
#+HTML_HEAD_EXTRA: body{font-family: Tahoma, Verdana, Arial, sans-serif;}

[[http://liballeg.github.io/images/logo.png]]

Interface and complete bindings to the [[https://liballeg.github.io/][Allegro 5 game programming library]].

Check out how the [[./src][source code]] is organized and compare it to the [[https://liballeg.github.io/a5docs/trunk/][API
reference]].

* Requires
- [[https://sourceware.org/libffi/][libffi]]
- [[https://liballeg.github.io/][liballegro5]]

* Quickstart
1. ~al_*~ becomes ~al:*~
2. [[./src/constants/][Constants]] and [[./src/types][types]] are shortened too, check the source code if you need help finding them
3. ~(al:rest secs)~ is ~(al:rest-time secs)~ because of symbol clash with ~#'cl:rest~
4. To access slots from a C struct, you can use ~CFFI:MEM-REF~ generate a plist
#+BEGIN_SRC lisp
(cffi:defcstruct display-mode
(width :int)
(height :int)
(format :int)
(refresh-rate :int))

(cffi:with-foreign-object (test '(:struct display-mode))
(let ((plist (cffi:mem-ref test '(:struct display-mode))))
(print plist)
(print (getf plist 'width))))
#+END_SRC
5. I've got a neat *OPTIONAL* [[./src/interface/interface.lisp][lispy interface]] which provides an entire fixed timestep game loop
6. Everything else is pretty much 1-to-1
7. If you're getting crashes on Mac OS X, put all your code into [[https://common-lisp.net/project/cffi/manual/html_node/defcallback.html][callback]] and pass it to [[https://www.allegro.cc/manual/5/al_run_main][al:run-main]]
8. [[./examples][Examples]] exist if you get lost

* Projects
Various projects I've found using cl-liballegro. Feel free to add items onto the list!

** GUI / UI
- [[https://github.com/lockie/cl-liballegro-nuklear][cl-liballegro-nuklear]] - Bindings to the [[https://github.com/Immediate-Mode-UI/Nuklear][nuklear]] immediate mode GUI library

** Games
- [[https://awkravchuk.itch.io/cycle-of-evil][Cycle of Evil]] - A fantasy-themed strategy/simulation with indirect player control
- [[https://awkravchuk.itch.io/mana-break][Mana Break]] - Indirect colony simulator
- [[https://awkravchuk.itch.io/thoughtbound][Thoughtbound]] - Post-modern dungeon crawler in fantasy setting
- [[https://awkravchuk.itch.io/darkness-looming-the-dawn][Darkness Looming: The Dawn]] - Old school hack n' slash
- [[https://github.com/xFA25E/simple-asteroids][simple-asteroids]] - Simple asteroids
- [[https://github.com/VyacheslavMik/tanks][tanks]] - Tanks

** Engine
- [[https://github.com/lockie/d2clone-kit][d2clone-kit]] - Diablo 2 clone game engine

** Templates
- [[https://github.com/lockie/cookiecutter-lisp-game][cookiecutter-lisp-game]] - Cookiecutter template for a game

** Tutorials
- [[https://gitlab.com/lockie/cl-fast-ecs/-/wikis/tutorial-1][Gamedev in Lisp part 1]], [[https://gitlab.com/lockie/cl-fast-ecs/-/wikis/tutorial-2][part 2]] - Tutorials on ECS game architecture featuring cl-liballegro

* General
[[https://user-images.githubusercontent.com/2598904/96662425-f3c4cf00-1313-11eb-9e59-807e27697c20.png]]

The most basic usage is 1-to-1 just uses the bindings "as is" such as
in this [[./examples/001-simple-window.lisp][example]].

Names have been changed to use a more lispy convention in which ~_~ is
converted to ~-~. In most cases function names match like
~al_flip_display(display);~ becomes ~(al:flip-display display)~

However types, constants, and structures have been shortened for user
convenience. There's no exact rules for it, but usually any prefix
with ~ALLEGRO_*~ or ~al_*~ is truncated because Common Lisp has
multiple namespaces to handle naming clashes. For the rare edge
cases, check the source code definitions for [[./src/constants/][constants]] and [[./src/types][types]].

Another change is that certain constants have been changed to Common
Lisp keywords. Keyboard functions in C use an enum values
corresponding to the key but cl-liballegro uses keywords instead. An
example is ~ALLEGRO_KEY_K~ becoming ~:K~. CFFI takes care of
translating the value to the keyword and vice-versa. Using keywords
over constants tends to be convenient in practice.

** CFFI
Occasionally dropping down to a level lower using CFFI is necessary.
One of these situations is passing a non-opaque data structure by
reference.

Consider this block of C:
#+begin_src c
{
ALLEGRO_EVENT event;
bool running = true;
while (running) process_event(&event);
}
#+end_src

In Common Lisp we will use CFFI to allocate the structure for the
corresponding Allegro 5 functions. Remember to free up the memory
afterwards!

#+begin_src lisp
(defparameter *running-p* t)
(let ((event (cffi:foreign-alloc '(:union al:event)))
(loop while *running-p* do (process-event event))
(cffi:foreign-free event))
#+end_src

** Orphaned Windows / Cleaning up Windows
At times when something goes wrong the debugger pops up and a new
window is created without the previous one being destroyed. This is
due to how Common Lisp debugger restarts execution. One of the ways
to handle this is wrapping things in an ~UNWIND-PROTECT~ or using the
condition handlers in Common Lisp. Errors should be handled in such a
way that restarts do not re-execute certain s-exps to create a new
display. Errors can also be handled by cleaning up resources.

** Optional Lisp Interface
An optional lisp interface is included with cl-liballegro which
provides a full game loop with a fixed timestep and Entity Component
System (ECS) implemented on the CLOS. Note that it is provided as is
and not optimized. If performance is a concern, it is recommended to
implement your own game loop while avoiding multiple dispatch and I
will look forward to seeing your AAA game in the future.

1. Define system which holds state
#+begin_src lisp
;; Creates a 800x600 resizable OpenGL display titled "Simple"
;; Fixed timestep loop runs logic at 1 FPS
;; The remaining time is spent on render
;;
;; The PREVIOUS-KEY slot is user-defined state for this example
(defclass window (al:system)
((previous-key :initform "Nothing" :accessor previous-key))
(:default-initargs
:title "Simple"
:width 800 :height 600
:logic-fps 1
:display-flags '(:windowed :opengl :resizable)
:display-options '((:sample-buffers 1 :suggest)
(:samples 4 :suggest))))
#+end_src

2. Implement Method for Logic Step
#+begin_src lisp
(defmethod al:update ((sys window))
(print 'one-logic-frame))
#+end_src

3. Implement Method for Render Step
#+begin_src lisp
(defmethod al:render ((sys window))
(al:clear-to-color (al:map-rgb 20 150 100))
(al:flip-display))
#+end_src

4. Implement Methods(s) for Event Handling
#+begin_src lisp
;; The lisp interface runs handlers during the logic step
;; Handlers are defined according to allegro events
(defmethod al:key-down-handler ((sys window))
(let ((keyboard (cffi:mem-ref (al:event sys) '(:struct al:keyboard-event))))
(print (getf keyboard 'al::keycode))
(setf (previous-key sys) (getf keyboard 'al::keycode))))
#+end_src

5. Run system
#+begin_src lisp
(al:run-system (make-instance 'window)))
#+end_src

** Mac OS X - Main UI Thread
Running on Mac OS X tends to behave oddly with threads because it
requires GUI related code to run in the main thread (affects programs
outside of Common Lisp too). The Allegro 5 library has a solution
with [[https://liballeg.github.io/a5docs/trunk/misc.html#al_run_main][al_run_main]]. Define a callback with [[https://common-lisp.net/project/cffi/manual/html_node/defcallback.html][defcallback]] and pass it to
~AL:RUN-MAIN~.

#+begin_src lisp
;; First define a callback
(cffi:defcallback my-main :void ()
;; Code goes in here
(function-with-gui-code))

;; Second execute by passing the callback to AL:RUN-MAIN
(al:run-main 0 (cffi:null-pointer) (cffi:callback my-main))
#+end_src

** Ignoring Floating Point Calculation Errors / Traps
Common Lisp implementations tend to throw floating point calculation
errors such as ~FLOATING-POINT-OVERFLOW~ and
~FLOATING-POINT-INVALID-OPERATION~ by default (called traps) to be
explicitly handled rather than ignored. There are situations where
this is valid behaviour but sometimes such errors get thrown despite
valid code being called through the foreign function interface (FFI).

In this case it should be safe to ignore using implementation specific
routines or the [[https://github.com/Shinmera/float-features/][float-features]] portability library:

#+begin_src lisp
;; SBCL
;; Sets traps globally
(sb-int:set-floating-point-modes :traps (:invalid :inexact :overflow))

;; SBCL
;; Code wrapped in the macro ignores floating point errors in the list
(sb-int:with-float-traps-masked (:invalid :inexact :overflow)
(function-with-floating-point-errors))

;; float-features (portability library)
;; Code wrapped in the macro ignores floating point errors in the list
(float-features:with-float-traps-masked (:divide-by-zero
:invalid
:inexact
:overflow
:underflow)
(function-with-floating-point-errors))
#+end_src

** Windows - Library Paths
There are path problems in Windows because the Allegro 5 library files
which contain all the functions the CFFI calls upon do not have a
default location unlike Unix environments. When the library is loaded
under Windows, CFFI will look for the library files in the *current
folder* of the FILE.LISP that evaluates ~(ql:quickload
"cl-liballegro")~. This means a copy of the library files must be in
the directory of FILE.LISP, not in the cl-liballegro directory unless
the FILE.LISP is in there. SLIME however, likes to change the default
search folder to the one Emacs is in when it starts.

*** With SBCL
#+BEGIN_SRC
;; Open command prompt in the folder that contains both the DLL and game.lisp
> sbcl
> (load "game.lisp") ; File contains (ql:quickload "cl-liballegro")
#+END_SRC

*** With Emacs + SLIME
/game.lisp contains (ql:quickload :cl-liballegro)/
#+BEGIN_SRC
;; Looks for the DLL at /path/to/Desktop/allegro.dll
C-x C-f /path/to/Desktop/file9.lisp
M-x slime
C-x C-f /path/to/Desktop/game/game.lisp
C-c C-l
#+END_SRC

#+BEGIN_SRC
;; Looks for the DLL at /path/to/Desktop/game/allegro.dll
C-x C-f /path/to/Desktop/file9.lisp
C-x C-f /path/to/Desktop/game/game.lisp
M-x slime
C-c C-l
#+END_SRC

#+BEGIN_SRC
;; Looks for the DLL at /whatever/default/emacs/directory/allegro.dll
M-x slime
C-x C-f /path/to/Desktop/game/game.lisp
C-c C-l
#+END_SRC

** File streams
There are [[https://www.cliki.net/gray%20streams][Gray streams]] wrapping liballegro [[https://liballeg.github.io/a5docs/trunk/file.html][file IO APIs]]:
#+begin_src lisp
;; text stream
(with-open-stream (stream (al:make-character-stream "credits.txt"))
(uiop:slurp-stream-lines stream))

;; binary stream
(with-open-stream (stream (al:make-binary-stream "loot.ase"))
(let ((result (make-array (al:stream-size stream)
:element-type '(unsigned-byte 8))))
(read-sequence result stream)
result))
#+end_src

Note: those can be particularly useful when combined with the [[https://liballeg.github.io/a5docs/trunk/physfs.html][liballegro
PhysicsFS addon]], which can help with reading files located within game
archives, such as Quake PAK files, zip archives [[https://icculus.org/physfs][etc]].

To mount such an archive as a folder, use the [[https://icculus.org/physfs/docs/html/physfs_8h.html#a8eb320e9af03dcdb4c05bbff3ea604d4][PHYSFS_mount]] function from
=libphysfs= library (usually dynamically linked to =liballegro=, except in official
Windows builds, where it is statically linked):
#+begin_src lisp
#-win32 (progn
(cffi:define-foreign-library libphysfs
(:darwin (:or "libphysfs.3.0.2.dylib" "libphysfs.1.dylib"))
(:unix (:or "libphysfs.so.3.0.2" "libphysfs.so.1"))
(t (:default "libphysfs")))
(cffi:use-foreign-library libphysfs))

(cffi:defcfun ("PHYSFS_mount" physfs-mount) :int
(new-dir :string) (mount-point :string) (append-to-path :int))

(assert (not (zerop (physfs-mount "archive.zip" (cffi:null-pointer) 1))))
;; now al:make-character-stream and al:make-binary-stream are able to
;; open files from archive.zip
#+end_src

* Contributing / Developing / Hacking
cl-liballegro is organized according to the [[https://liballeg.github.io/a5docs/trunk/][Allegro 5 Documentation]]
with functions, types, and constants separated.

[[https://cffi.common-lisp.dev/][CFFI]] is used and its [[https://cffi.common-lisp.dev/manual/index.html][manual]] recommended to understand more advanced
uses though not required for most cases.

Naming conventions has a preference for truncating ~ALLEGRO~ or ~al~
for user convenience since Common Lisp has multiple namespaces for
resolving symbol names. For the rare edge cases, check the [[./src/types/][types]] and
[[./src/constants/][constants]]

Usage of keywords over enums preferred for user convenience.

** Project Structure
- [[./src/constants/]]: Allegro 5 constants, enums, and flag definitions
- [[./src/ffi-functions/]]: Allegro 5 function definitions
- [[./src/types/]]: Allegro 5 type definitions
- [[./src/interface/]]: Common Lisp interface definition, optional fixed timestep
game loop implemented with CLOS, Gray streams wrapping file APIs.
- [[./src/package.lisp]]: Common Lisp package definition, exports usable symbols
- [[./src/library.lisp]]: CFFI library definition, loads Allegro 5 library files into memory
- [[./cl-liballegro.asd]]: ASDF project definition, specifies source files to be loaded

** Checklist
- [ ] New bindings added for export to [[./src/package.lisp][package defintion]]
- [ ] New source files added for loading to the [[./cl-liballegro.asd][project definition]]
- [ ] Bump version and add description of changes

* [[./CHANGELOG.org][CHANGELOG]]
FYI these bindings are so stable it can make the repo look dead

* [[https://github.com/resttime/cl-liballegro/issues][Support / Help / Bug Reports]]

* License
Project under zlib license