Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/vydd/sketch
A Common Lisp framework for the creation of electronic art, visual design, game prototyping, game making, computer graphics, exploration of human-computer interaction, and more.
https://github.com/vydd/sketch
2d art common-lisp games graphics hci sketch visual
Last synced: about 1 month ago
JSON representation
A Common Lisp framework for the creation of electronic art, visual design, game prototyping, game making, computer graphics, exploration of human-computer interaction, and more.
- Host: GitHub
- URL: https://github.com/vydd/sketch
- Owner: vydd
- License: mit
- Created: 2015-11-02T03:59:35.000Z (about 9 years ago)
- Default Branch: master
- Last Pushed: 2024-06-19T17:09:02.000Z (6 months ago)
- Last Synced: 2024-10-10T16:43:28.662Z (2 months ago)
- Topics: 2d, art, common-lisp, games, graphics, hci, sketch, visual
- Language: Common Lisp
- Homepage:
- Size: 1.45 MB
- Stars: 1,406
- Watchers: 46
- Forks: 67
- Open Issues: 33
-
Metadata Files:
- Readme: README.org
- License: LICENSE
Awesome Lists containing this project
- awesome-cl - Sketch - A CL framework for the creation of electronic art, graphics, and lots more. [MIT][200]. (Miscellaneous ##)
README
* Sketch
[[http://quickdocs.org/sketch/][file:http://quickdocs.org/badge/sketch.svg]]
Sketch is a Common Lisp environment for the creation of electronic art, visual design, game prototyping, game making, computer graphics, exploration of human-computer interaction and more. It is inspired by [[https://processing.org][Processing Language]] and shares some of the API.
[[http://i.imgur.com/MNZUwz8.png]]
** Installation
Sketch is available through [[https://www.quicklisp.org/beta/][Quicklisp]], Common Lisp's de facto package manager. From your REPL, run:
#+BEGIN_SRC lisp
(ql:quickload :sketch)
#+END_SRCTo make Sketch run correctly, however, a few requirements must be met.
*** Requirements
**** Common Lisp Implementation
Sketch should be compatible with all major Common Lisp implementations and all major operating systems - more specifically, all CL implementations and operating systems that [[https://github.com/lispgames/cl-sdl2][cl-sdl2]] runs on. Incompatibility with any of these is considered a bug.Sketch is known to work with:
- CCL 1.11 on Mac OS X El Capitan
- CCL 1.12.1 on MacOS 13.1 ([[https://github.com/vydd/sketch/issues/67][steps]])
- CCL SVN 1.12.dev.r16617 on Arch Linux
- CCL 1.11 on Windows 10 64bit
- SBCL on Debian Unstable
- SBCL 1.2.16 on Arch Linux
- SBCL 1.3.1 on Linux Mint 17
- SBCL 1.3.6 on Windows 10 64bitWorkarounds, or extra steps, may be required on some systems:
- Arch Linux, [[https://github.com/vydd/sketch/issues/16][issue]].
- OpenSuse, [[https://github.com/vydd/sketch/issues/17][issue]].
- CCL on OSX: Make sure to use the 64-bit version of CCL ([[https://github.com/vydd/sketch/issues/23][issue]]).
- Quickload fails with libffi error, [[https://github.com/vydd/sketch/issues/47][issue]].Sketch is known to *not* work with:
- SBCL 1.2.15 on Mac OS X
/Sketch can't handle input and the window's titlebar is black. These kinds of issues are a known problem with Mac OS X, because it needs its GUI threads to be main, and CCL is the only lisp that accounts for that out of the box. There are ways to counter this, but until a solution finds its way into this repository, SBCL on Mac OS X will stay on this list. In the meantime, use CCL./If you test Sketch on other systems, please send a pull request to include your results.
**** Foreign dependencies
***** SDL2
SDL2 is currently Sketch's only backend. It is a C library which you will need to download manually from [[https://www.libsdl.org][libsdl webpage]]. Select the release compatible with your operating system, or compile from the source code.***** SDL2 Image & SDL2 TTF
For loading image and font files, Sketch relies on SDL2 Image and SDL2 TTF, respectively, both part of the SDL project.***** libffi
Some users have reported that [[https://sourceware.org/libffi/][libffi]] needed to be installed to make Sketch work.***** OpenGL
Sketch requires graphics hardware and drivers with support for GL version 3.3.**** Installing and running Sketch on Windows
Sketch works on both CCL and SBCL, but installing all prerequisites might not be as straightforward as it is on the other platforms.***** Libraries
Download SDL2, SDL2_IMAGE and SDL2_TTF dlls from [[https://www.libsdl.org][libsdl webpage]] and copy them somewhere Windows can find them - =\Windows\System32= will work. When copying SDL2_TTF, make sure to copy all of the dlls provided in the archive, and not just the TTF one.Now you will need to get a libffi dll. One of the ways of doing this is compiling from the source, but for a quick and easy solution, you can just find a trusted source and use their version. For example, if you are using Emacs on Windows, you can find =libffi-6.dll= in =emacs\bin=. Copy it to the same directory you copied sdl2 dlls to earlier.
***** GCC
To bootstrap cffi-libffi, you are going to need a C compiler, more specifically the one from the GNU Compiler Collection. Also, libffi headers and pkg-config are needed. Luckily, you can get all these things (and more) with MSYS2. Go to [[https://msys2.github.io]] and follow the instructions for installing the 64bit version.From its console, install gcc, libffi headers and pkg-config by running =pacman -S gcc libffi libffi-devel pkg-config=.
***** Environment variables
From the Control Panel, open System properties, go to the Advanced tab, and click "Environment Variables..." - or click the Start button, start typing "environment" and select "Edit the system environment variables".Double click "Path" from the list of System variables and make sure that both your lisp implementation's path (something like =C:\Program Files\Steel Bank Common Lisp\1.3.6\=) and MSYS path (probably =C:\msys64\usr\bin=) are listed. If not, click "New" and add them now.
If you needed to change anything here, restart the computer now.
***** SLIME
If you are using SLIME, you won't be able to load or run Sketch if you start SWANK from emacs (by running =M-x slime=). Instead, you should open the Command Prompt (the regular one, not MSYS), start your lisp and eval =(ql:quickload :swank)= =(swank:create-server)=. From Emacs, type =M-x slime-connect=, and finally, press enter twice (for localhost and port 4005).If you did everything correctly, you should be able to =(ql:quickload :sketch)= and move on to the tutorial.
*** Running provided examples
To get a feel for what Sketch can do, and also to make sure that everything has been installed correctly, run the examples as follows.#+BEGIN_SRC lisp
CL-USER> (ql:quickload :sketch-examples)
CL-USER> (make-instance 'sketch-examples:hello-world)
CL-USER> (make-instance 'sketch-examples:sinewave)
CL-USER> (make-instance 'sketch-examples:brownian)
CL-USER> (make-instance 'sketch-examples:life) ; Click to toggle cells,
; any key to toggle iteration
CL-USER> (make-instance 'sketch-examples:input)
CL-USER> (make-instance 'sketch-examples:stars)
#+END_SRC*** Running example code from this page
In all the following examples, we're going to assume that Sketch is loaded with =(ql:quickload :sketch)=, and that we're in package =:TUTORIAL=, which is set to use =:SKETCH=.#+BEGIN_SRC lisp
CL-USER> (ql:quickload :sketch)
CL-USER> (defpackage :tutorial (:use :cl :sketch))
CL-USER> (in-package :tutorial)
TUTORIAL> ;; ready
#+END_SRC** Tutorial
Defining sketches is done with the =defsketch= macro, which is essentially a wrapper for =defclass=.#+BEGIN_SRC lisp
(defsketch tutorial ())
(make-instance 'tutorial)
#+END_SRCIf all goes well, this should give you an unremarkable gray window. From now on, assuming you're using Emacs + SLIME, or a similarly capable environment, you can just re-evaluate =(defsketch tutorial () )= and the sketch will be restarted without you having to close the window or make another instance of the class.
*** Shapes
Let's draw something! Drawing code goes inside the body of =defsketch=.=(rect x y w h)= draws a rectangle where =x= and =y= specify the top-left corner of the rectangle, and =w= and =h= are the width and height. By default, the origin (0, 0) is at the top-left corner of the drawing area, and the positive y direction is facing down.
#+BEGIN_SRC lisp
(defsketch tutorial ()
(rect 100 100 200 200))
#+END_SRC#+BEGIN_SRC lisp
(defsketch tutorial ()
(dotimes (i 10)
(rect 0 (* i 40) (* (+ i 1) 40) 40)))
#+END_SRCSomething to note: drawing code doesn't need to go into a special function or method, or be explicitly binded to a sketch. =defsketch= is defined as =(defsketch sketch-name bindings &body body)=: that body, and any functions it calls to, is your drawing code. We will get to =bindings= later.
Circles and ellipses are drawn with =(circle x y r)= and =(ellipse cx cy rx ry)=:
#+BEGIN_SRC lisp
(defsketch tutorial ()
(circle 300 100 50)
(ellipse 200 200 100 50))
#+END_SRCLines with =(line x1 y1 x2 y2)=:
#+BEGIN_SRC lisp
(defsketch tutorial ()
(line 0 0 400 400)
(line 400 0 0 400))
#+END_SRCLines with an arbitrary number of segments with =polyline=:
#+BEGIN_SRC lisp
(defsketch tutorial ()
(polyline 100 100 200 150 300 100
200 200 100 100))
#+END_SRCArbitrary polygons can be drawn using =(polygon x1 y1 x2 y2 ...)=, the winding rule (how the "inside parts" and "outside parts" are determined) is specified as a pen property (pens will be described in more detail later) and can be one of =(:odd :nonzero :positive :negative :abs-geq-two)=. By default, it's =:nonzero=.
#+BEGIN_SRC lisp
(defsketch tutorial ()
(with-pen (make-pen :fill +blue+ :winding-rule :odd)
(polygon 100 100 200 150 300 100 200 200)))
#+END_SRCTo draw a regular polygon with =n= sides, call =(ngon n cx cy rx ry &optional (angle 0))=; =cx= and =cy= are the coordinates of the center of the shape, while =rx= and =ry= are height of an ellipse that the shape is inscribed inside.
#+BEGIN_SRC lisp
(defsketch tutorial ()
(dotimes (i 4)
(ngon (+ i 3) (+ 50 (* i 100)) 200 20 20 (* i 20))))
#+END_SRCBezier curves with 4 control points are drawn with =(bezier x1 y1 bx1 by1 bx2 by2 x2 y2)=; =x1=, =y1=, =x2= and =y2= determine the start and end points.
#+BEGIN_SRC lisp
(defsketch tutorial ()
(bezier 0 400 100 100 300 100 400 400))
#+END_SRCThe resolution of a curve can be controlled with the pen property =:curve-steps=, for example:
#+BEGIN_SRC lisp
(defsketch tutorial ()
(with-pen (make-pen :curve-steps 4 :stroke +white+)
(bezier 0 400 100 100 300 100 400 400)))
#+END_SRC*** Configuring your sketch
The first form in =defsketch= after the name of your sketch, and before the body, is a list of bindings that will be available in the sketch body. This is also where a number of configuration options can be set:- =title= (string): window title.
- =width= and =height= (in pixels): window dimensions, 400 x 400 by default.
- =fullscreen= (=t= or =nil=): whether window is fullscreen.
- =resizable= (=t= or =nil=): whether window is resizable.
- =copy-pixels= (=t= or =nil=): if true, the screen is not cleared before each drawing loop.
- =y-axis= (=:down= or =:up=): =:down= by default. Determines both the location of the origin and the positive direction of the y-axis. =:down= means (0,0) is in the top-left corner and greater values of =y= move down the screen. =:up= means (0,0) is in the bottom-left corner and greater =y= values go up.
- =close-on= (a keyword symbol denoting a key, or =nil= to disable): a shortcut for closing the sketch window, =:escape= by default. Set to =nil= to disable. The key names (e.g. =:space=, =:g=) are based on SDL2 scancodes, see [[https://wiki.libsdl.org/SDL2/SDL_Scancode][here]].#+BEGIN_SRC lisp
(defsketch tutorial
((radius 10)
(resizable t)
(width 200))
(circle (/ width 2) (/ radius 2) radius))
#+END_SRC*** Colors
In the previous examples, you may have noticed how to draw a shape with a fill color. Let's now explore the color capabilities of Sketch in more detail. To draw a yellow background:#+BEGIN_SRC lisp
(defsketch tutorial ()
(background +yellow+))
#+END_SRC**** Predefined colors
There are constants for commonly used colors: =+RED+=, =+GREEN+=, =+BLUE+=, =+YELLOW+=, =+MAGENTA+=, =+CYAN+=, =+ORANGE+= =+WHITE+=, and =+BLACK+=.**** RGB, HSB, GRAY
You can create other colors using =(rgb red green blue &optional (alpha 1.0))=, =(hsb hue saturation brightness &optional (alpha 1.0))= or =(gray amount &optional (alpha 1.0))=. The arguments to these functions are values from 0 to 1. =(gray amount &optional (alpha 1.0))= is really just a convenient alias for =(rgb amount amount amount &optional (alpha 1.0))=.More information:
- [[https://en.wikipedia.org/wiki/RGB_color_model][RGB color model]]
- [[https://en.wikipedia.org/wiki/HSL_and_HSV][HSB / HSV]]./This might be a good place to note that function names in Sketch use the American English spellings, like "gray" and "color". It's just a choice that needed to be made, in pursuit of uniformity and good style./
For a lighter yellow:
#+BEGIN_SRC lisp
(defsketch tutorial ()
(background (rgb 1 1 0.5)))
#+END_SRCAll color functions have an additional =ALPHA= parameter that determines the transparency.
**** RGB-255, HSB-360, GRAY-255
Sometimes it's easier to think about color values in non-normalized ranges. That's why Sketch offers =RGB-255=, =HSB-360=, and =GRAY-255=.This is how these functions map to their normalized variants.
| (rgb-255 r g b a) | (rgb (/ r 255) (/ g 255) (/ b 255) (/ a 255)) |
| (hsb-360 h s b a) | (hsb (/ h 360) (/ s 100) (/ b 100) (/ a 255)) |
| (gray-255 g a) | (gray (/ g 255) (/ a 255)) |=HSB-360= uses different ranges, because hue is represented in degrees (0-360), and saturation and brightness are represented as percentages (0-100).
**** HEX-TO-COLOR
If you are used to working with colors in hex, like in CSS, you can use =(hex-to-color string)=, where =STRING= is the color in one of the following formats: "4bc", "#4bc", "4bcdef", or "#4bcdef".**** Generating colors
If you don't care about fiddling with the exact values, but still need different colors, you can use one of the following functions.***** =(lerp-color (start-color end-color amount &key (mode :hsb)))=
Lerp is a shorthand for [[https://en.wikipedia.org/wiki/Linear_interpolation][linear interpolation]]. This function takes the starting color and the ending color, and returns the color between them, which is an =AMOUNT= away from the starting color. When =AMOUNT= equals zero, the returned color equals the starting color, and when =AMOUNT= equals one, the ending color is returned. Amounts between zero and one give colors that are "in-between". These colors are calculated according to the specified =MODE=, which is =:HSB= by default, meaning that the resulting color's hue is between the starting and ending hue, as is the case with its saturation and brightness.#+BEGIN_SRC lisp
(defsketch lerp-test ((title "lerp-color") (width 400) (height 100))
(dotimes (i 4)
(with-pen (make-pen :fill (lerp-color +red+ +yellow+ (/ i 4)))
(rect (* i 100) 0 100 100))))
#+END_SRC***** =(random-color (&optional (alpha 1.0)))=
Returns a random color. You probably don't want to use this, because many of the returned colors will be either too dark, or too light. You do get to choose the =ALPHA= value, though.#+BEGIN_SRC lisp
(defparameter *colors* (loop for i below 16 collect (random-color)))(defsketch random-color-test ((title "random-color") (width 400) (height 100))
(dotimes (x 8)
(dotimes (y 2)
(with-pen (make-pen :fill (elt *colors* (+ x (* y 8))))
(rect (* x 50) (* y 50) 50 50)))))
#+END_SRC***** =(hash-color (n &optional (alpha 1.0)))=
This is probably the function you're looking for, if you just want to create a non-repeating set of colors quickly. It maps all numbers to "interesting" (not too dark, not too light) colors. You can use this for coloring procedurally generated objects, when prototyping and just trying to make things look different quickly, when making palettes, looking for "the right" color, and many other things.#+BEGIN_SRC lisp
(defsketch hash-color-test ((title "hash-color") (width 400) (height 100))
(dotimes (i 128)
(with-pen (make-pen :fill (hash-color i))
(rect (* i (/ 400 128)) 0 (/ 400 128) 100))))
#+END_SRC**** Color filters
Sometimes you have a color, and would like to transform it in some way. That's what color filters are for.***** Grayscale
To convert colors to grayscale, you can use =color-filter-grayscale=. Two modes of grayscale conversion are implemented:- =:luminosity=, the default, which is [[https://en.wikipedia.org/wiki/Grayscale#Colorimetric_.28luminance-preserving.29_conversion_to_grayscale][luminance-preserving]]
- =:average=, which sets all color channels to their average#+BEGIN_SRC lisp
(defsketch grayscale-test ((title "grayscale") (width 400) (height 300))
(dotimes (i 10)
(let ((color (hash-color i)))
(with-pen (make-pen :fill (color-filter-grayscale color))
(rect (* i 40) 0 40 100))
(with-pen (make-pen :fill color)
(rect (* i 40) 100 40 100))
(with-pen (make-pen :fill (color-filter-grayscale color :average))
(rect (* i 40) 200 40 100)))))
#+END_SRC***** Invert
To invert a color, use =color-filter-invert=:#+BEGIN_SRC lisp
(defsketch invert-test
((title "invert") (width 300) (height 300) (i 0))
(background +white+)
(incf i 0.01)
(let ((color (rgb (abs (sin i)) (abs (cos i)) 0)))
(with-pen (make-pen :fill color)
(circle 100 150 50))
(with-pen (make-pen :fill (color-filter-invert color))
(circle 200 150 50))))
#+END_SRC***** Rotate
Rotating a color in Sketch using =color-filter-rotate= sets the value of its red channel to the
previous value of the green channel; green to blue, and blue to
red. The operation is intended to be used in palette generation,
because the rotated colors usually work pretty well together.#+BEGIN_SRC lisp
(defsketch rotate-test
((title "rotate") (width 300) (height 300)
(i 0) (color (rgb 0.2 0.8 1.0)))
(background +white+)
(incf i 1)
(when (zerop (mod i 60))
(setf color (color-filter-rotate color)))
(with-pen (make-pen :fill color)
(rect 100 100 100 100)))
#+END_SRC***** HSB
[[https://en.wikipedia.org/wiki/HSL_and_HSV][HSB]] stands for Hue/Saturation/Brightness. You can use
=color-filter-hsb= to adjust hue, saturation and brightness of an existing color.#+BEGIN_SRC lisp
(defsketch hsb-test
((title "hsb") (width 400) (height 300) (color (rgb 0.2 0.5 0.6)))
(dotimes (i 4)
(with-pen (make-pen :fill (color-filter-hsb color :hue (* 0.1 (+ i 1))))
(rect (* i 100) 0 100 100))
(with-pen (make-pen :fill (color-filter-hsb color :saturation (* 0.1 (+ i 1))))
(rect (* i 100) 100 100 100))
(with-pen (make-pen :fill (color-filter-hsb color :brightness (* 0.1 (+ i 1))))
(rect (* i 100) 200 100 100))))
#+END_SRC*** Pens
Pens are used to draw shapes. If no pen is specified, the default pen sets =:fill= to white, =:stroke= to black, and =weight= to 1.***** Creating and Using Pens
Say you want to draw a red square and a blue circle. You would need to use two different pens.
#+BEGIN_SRC lisp
(defsketch pen-test
((title "pens"))
(with-pen (make-pen :fill +red+)
(rect 100 100 100 100)) ; this rect will be red
(with-pen (make-pen :fill +blue+)
(circle 315 315 50))) ; this rect will be blue
#+END_SRC***** Fill/Stroke
The squares in the previous example were filled because we specified the =:fill= property in =make-pen=.
If we wanted to just draw the outline of the square, we would use =:stroke= like this:
#+BEGIN_SRC lisp
(defsketch outline-square
((title "Outline Square"))
(with-pen (make-pen :stroke +red+)
(rect 100 100 100 100)))
#+END_SRC
#+BEGIN_SRC lisp
(defsketch fill-stroke
((title "Fill and Stroke"))
(background +white+)
(with-pen (make-pen :stroke (rgb .5 0 .6) :fill (rgb 0 .8 .8))
(rect 50 50 100 75)
(circle 300 220 100)))
#+END_SRC***** Weight
We can also change the thickness of the lines and shapes that we draw by changing the pen =:weight=.
#+BEGIN_SRC lisp
(defsketch weight-test
((title "Weight Test"))
(dotimes (i 10)
(with-pen (make-pen :stroke +white+ :weight (+ i 1)) ; pen weight can't be zero
(line 50 (* i 20) 350 (* i 20)))))
#+END_SRC**** Curve-steps
=:curve-steps= is used to change the smoothness (resolution) of curves like =#'bezier=.
#+BEGIN_SRC lisp
(defsketch curve-test
((title "Curve-steps"))
(dotimes (i 99)
(with-pen (make-pen :stroke +red+ :curve-steps (+ i 1)) ; as curve-step increases, curve becomes "smoother"
(bezier 0 400 100 100 300 100 400 400))))
#+END_SRC*** Transforms
The transforms =(translate dx dy)=, =(rotate angle &optional (cx 0) (cy 0))= and =(scale sx &optional sy (cx 0) (cy 0))= are available to change the view matrix that is applied to coordinates.Macros =(with-translate (dx dy) &body body)=, =(with-rotate (angle &optional (cx 0) (cy 0)) &body body)= and =(with-scale (sx &optional sy (cx 0) (cy 0)) &body body)= can be used to restore the view matrix after executing the body.
The current view can also be saved on a stack and restored with =(push-matrix)= and =(pop-matrix)=, which are analogous to =push()= and =pop()= in p5.js. The macro =(with-identity-matrix &body body)= pushes the current view matrix onto the stack, sets the view matrix to the identity matrix, executes =body=, and then pops the view matrix. =(with-current-matrix &body body)= is the same, except it doesn't change the view matrix after pushing it.
In this example, translation and rotation are used to draw a triangle in the centre of the screen, without explicitly defining the coordinates of the vertices.
#+BEGIN_SRC lisp
(defsketch transform-test
((title "Transform test")
(width 500)
(height 500)
(side 100)
(y-offset (/ side (* 2 (tan (radians 60))))))
(with-translate (250 250)
(loop repeat 3
do (line (- (* 1/2 side)) y-offset (* 1/2 side) y-offset)
do (rotate 120))))
#+END_SRCThis example draws a sequence of increasingly shrinking squares using scaling.
#+BEGIN_SRC lisp
(defsketch transform-test
((width 400)
(height 400)
(title "Scale test"))
(translate 100 100)
(dotimes (x 5)
(rect 0 0 100 100)
(translate 150 0)
(scale 1/2)))
#+END_SRC*** Text
Use =(text text-string x y &optional width height)= to draw text, where =x= and =y= specify the top-left corner of the rectangle containing the text. =width= and =height= control the shape of the text box. There is support for changing the [[https://github.com/vydd/sketch/blob/master/src/font.lisp#L29][font]].#+BEGIN_SRC lisp
(defsketch text-test
((title "Hello, world!"))
(text title 0 0 100))
#+END_SRCThe font can be specified using =(make-font &key face color size line-height align)= and the =with-font= macro.
#+BEGIN_SRC lisp
(defsketch text-test
((title (format nil "Hello, world!~%Next line"))
(with-font (make-font :color +white+
:face (load-resource "/path/to/font.ttf")
:size 12
:line-height 1
:align :left)
(text title 0 0 100)))
#+END_SRC=align= can be =:left=, =:centre= or =:right=, and determines whether the x & y coordinates correspond to the left end, centre, or right end of the text box. =line-height= determines the vertical space given to a line of text, scaled according to the font size, i.e. =:line-height 1= leaves just enough space so that the text on two lines won't overlap.
*** Images
First =(load-resource filename ...)= to load the image from a given file, then =(draw image &key x y width height)= to draw the image with its top-left corner at =(x, y)= and with the given =width= and =height=. If not provided, default =(x,y)= is =(0,0)= and =width= & =height= are taken from the image.#+BEGIN_SRC lisp
(defsketch image-test
((title "Hello, image!")
(pic (load-resource "/path/to/img.png")))
(draw pic :x 10 :y 10 :width 200 :height 200))
#+END_SRCNote that =load-resource= automatically caches the resource when it is called inside a valid sketch environment (i.e. inside the defsketch's body), so it is not inefficient to call it in every loop. It is important to release resources using =sketch::free-resource=; this is done automatically for resources in the sketch environment when the sketch window is closed. Finally, to avoid caching and to reload the resource every time, the parameter =:force-reload-p= can be passed to =load-resource=.
Images can be cropped using =(crop image x y w h)=, where =x= and =y= indicate the top-left corner of the cropping rectangle (relative to the top-left corner of the image) and =w= and =h= indicate the width & height. Image flipping can be accomplished by using negative =w= and =h= values.
*** Input
Input is handled by defining implementations of the methods listed below. Currently, it is not possible to call drawing functions from these methods, though this can be worked around by saving the input somewhere and then doing the drawing from the sketch body, as demonstrated in the examples to follow.- =(on-click instance x y)=, =(on-middle-click x y)= and =(on-right-click x y)= are called when there's a left, middle or right click. =x= and =y= give the coordinates of the click.
- =(on-mouse-button button state x y)= is called for left, middle and right mousebutton interactions. =button= can be one of =:left=, =:middle= and =:right=. =state= can be either =:up= or =:down=.
- Depending on the value of =button=, this propagates to one of: =(on-mouse-left state x y)=, =(on-mouse-middle state x y)=, or =(on-mouse-right state x y)=.
- These methods, in turn, propagate to =(on-mouse-left-up x y)=, =(on-mouse-right-down x y)=, =(on-mouse-right-down x y)=, ...
- =(on-hover instance x y)= is called when the mouse moves, =x= and =y= give its coordinates.
- =(on-text instance text)= is called when a single character is entered, =text= is a string consisting of just this character.
- =(on-key instance key state)= is called when a key is pressed. =key= is a keyword symbol denoting which key was pressed/released (like =:space= or =:left=; for now, the names are based on SDL2 scancodes, see [[https://wiki.libsdl.org/SDL2/SDL_Scancode][here]] for the full list), and =state= is a keyword symbol denoting whether the key was pressed (=:up=) or released (=:down=).In this example, we draw a new rectangle every time there is a click.
#+BEGIN_SRC lisp
(defsketch input-test
((title "Hello, input")
(rectangles nil))
(loop for (x y) in rectangles
do (rect x y 50 50)))
(defmethod on-click ((window input-test) x y)
(with-slots (rectangles) window
(push (list x y) rectangles)))
#+END_SRCIn this example, all keyboard text input is echoed to the screen.
#+BEGIN_SRC lisp
(defsketch text-test
((title "Hello, input")
(text-to-write nil))
(loop for s in text-to-write
do (text s 0 0 20 20)
do (translate 20 0)))
(defmethod on-text ((window text-test) text)
(with-slots (text-to-write) window
(setf text-to-write (nconc text-to-write (list text)))))
#+END_SRCFinally, here is an example where a pair of eyes follow the mouse (the pupils are restricted to a rectangle, it would look better if they were restricted to a circle).
#+BEGIN_SRC lisp
(defsketch hover-test
((looking-at (list 0 0))
(cx (/ width 2))
(cy (/ height 2)))
(let ((cx-1 (- cx 50))
(cx-2 (+ cx 50))
(mx (car looking-at))
(my (cadr looking-at)))
(with-pen (make-pen :fill +white+)
(ellipse cx-1 cy 40 80)
(ellipse cx-2 cy 40 80))
(with-pen (make-pen :fill +black+)
(flet ((move-towards (x1 x2)
(let ((diff (- x2 x1)))
(+ x1 (if (< (abs diff) 10)
diff
(* (signum diff) 10))))))
(circle (move-towards cx-1 mx) (move-towards cy my) 10)
(circle (move-towards cx-2 mx) (move-towards cy my) 10)))))
(defmethod on-hover ((window hover-test) x y)
(with-slots (looking-at) window
(setf (car looking-at) x
(cadr looking-at) y)))
#+END_SRCSee also: [[https://github.com/vydd/sketch/blob/master/examples/life.lisp][life.lisp]].
*** Setup
The generic function =(setup instance &key &allow-other-keys)= is a hook that gets called once on every "restart" of the sketch. That is:- before the drawing code in the sketch body is called for the first time.
- whenever the sketch is redefined.
- every time an error occurs.Note that any drawing that takes place within =setup= will be immediately covered by a gray background, unless =(copy-pixels t)= is added to =defsketch=.
Here is an example usage of =setup= from [[https://github.com/vydd/sketch/blob/master/examples/brownian.lisp][brownian.lisp]].
#+BEGIN_SRC lisp
(defmethod setup ((instance brownian) &key &allow-other-keys)
(background (gray 1)))
#+END_SRC*** Saving a picture
=(save-png pathname)= can be called within the body of =defsketch= to save a PNG of the currently running sketch. A keyboard shortcut could be set up to take screenshots, as follows.#+BEGIN_SRC lisp
(defsketch save-test
((should-save nil)
(copy-pixels t))
(rect (random width) (random height) 10 10)
(when should-save
(setf should-save nil)
(save-png "/tmp/my-sketch.png")))
(defmethod on-text ((window save-test) text)
(when (string= text "s")
(setf (slot-value window 'should-save) t)))
#+END_SRC*** Drawing with a canvas
=(make-canvas width height)= can be used to create a rectangular grid of pixels. The shape of the grid is defined by =width= and =height=.=(canvas-paint canvas color x y)= sets the color of a pixel within the grid.
=(canvas-lock canvas)= freezes the appearance of the canvas. Any calls to =(canvas-image canvas)= will show an image of the canvas when =canvas-lock= was last called.
=(canvas-unlock canvas)= allows the image of the canvas to be modified again.
=(draw canvas &key (x 0) (y 0) (width nil) (height nil)= draws the canvas; by default, the original width and height of the canvas are used, but these can be overridden.
Example: [[https://github.com/vydd/sketch/blob/master/examples/stars.lisp][stars.lisp]].
*** Control flow
=(stop-loop)= from within a sketch body or within an event handler to disable the drawing loop.=(start-loop)= to start the drawing loop again.
This can be used, for example, to draw a static sketch and then disable the drawing loop so as to not burn up your CPU. It can also be used to regenerate the sketch with each mouseclick.
Example: [[https://github.com/vydd/sketch/blob/master/examples/control-flow.lisp][control-flow.lisp]].
** Made with Sketch
- [[https://vydd.itch.io/qelt][QELT]]
- [[https://github.com/sjl/coding-math][sjl's implementation of coding math videos]]
- [[https://github.com/bufferswap/crawler2][Visual examples for axion's crawler2 library]]
- [[https://github.com/Kevinpgalligan/sketches][Generative art and other experiments by Kevin.]]** Outro
For everything else, read the code or ask vydd at #lispgames. Go make something pretty!